From b856d4ff549c37711ace84cd44d80bfe0af3d083 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 11:50:38 +0300 Subject: [PATCH] feat(notification): add Resend quota gate and waiting-for-reset state --- .env.example | 10 +- backend/config/config.go | 4 + backend/config/mail.go | 68 ++ backend/config/mail_test.go | 44 + .../00007_create_mail_quota_usage.sql | 110 +++ backend/db/queries/delivery.sql | 18 + backend/db/queries/mail_quota.sql | 193 ++++ backend/integration_test/mail_quota_test.go | 853 ++++++++++++++++++ .../postgres_migrations_test.go | 31 +- .../adapter/secondary/mail/resend/response.go | 20 +- .../adapter/secondary/mail/resend/sender.go | 7 + .../secondary/mail/resend/sender_test.go | 11 +- .../adapter/secondary/postgres/delivery.go | 30 + .../adapter/secondary/postgres/mail_quota.go | 369 ++++++++ .../secondary/postgres/sqlc/delivery.sql.go | 47 + .../secondary/postgres/sqlc/mail_quota.sql.go | 493 ++++++++++ .../adapter/secondary/postgres/sqlc/models.go | 24 + .../secondary/postgres/sqlc/querier.go | 50 + backend/internal/bootstrap/app.go | 5 +- backend/internal/bootstrap/mail_quota.go | 53 ++ backend/internal/bootstrap/mail_test.go | 4 + backend/internal/domain/mail_quota.go | 112 +++ backend/internal/domain/mail_quota_test.go | 120 +++ backend/internal/port/outbound/delivery.go | 17 + backend/internal/port/outbound/mail.go | 8 + backend/internal/port/outbound/mail_quota.go | 135 +++ backend/internal/port/outbound/transaction.go | 1 + .../usecase/notification/delivery_status.go | 79 ++ .../notification/delivery_status_test.go | 84 ++ .../internal/usecase/notification/quota.go | 340 +++++++ .../usecase/notification/quota_test.go | 572 ++++++++++++ deploy/docker/docker-compose.yml | 4 + docs/en/ARCHITECTURE.md | 59 +- docs/en/DEPLOY.md | 23 +- docs/en/DEVELOPMENT.md | 4 +- docs/en/TESTING.md | 38 +- docs/ru/ARCHITECTURE.md | 59 +- docs/ru/DEPLOY.md | 23 +- docs/ru/DEVELOPMENT.md | 4 +- docs/ru/TESTING.md | 38 +- 40 files changed, 4116 insertions(+), 48 deletions(-) create mode 100644 backend/db/migrations/00007_create_mail_quota_usage.sql create mode 100644 backend/db/queries/mail_quota.sql create mode 100644 backend/integration_test/mail_quota_test.go create mode 100644 backend/internal/adapter/secondary/postgres/mail_quota.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/mail_quota.sql.go create mode 100644 backend/internal/bootstrap/mail_quota.go create mode 100644 backend/internal/domain/mail_quota.go create mode 100644 backend/internal/domain/mail_quota_test.go create mode 100644 backend/internal/port/outbound/mail_quota.go create mode 100644 backend/internal/usecase/notification/delivery_status.go create mode 100644 backend/internal/usecase/notification/delivery_status_test.go create mode 100644 backend/internal/usecase/notification/quota.go create mode 100644 backend/internal/usecase/notification/quota_test.go diff --git a/.env.example b/.env.example index 13c2e4d..b2d9743 100644 --- a/.env.example +++ b/.env.example @@ -30,9 +30,17 @@ EMAIL_PROVIDER=disabled EMAIL_FROM=no-reply@example.com # Label of the provider account (lowercase letters, digits, ".", "_", "-"), # never the key. Every new delivery is pinned to EMAIL_PROVIDER and this -# label; change it whenever the key belongs to another provider account. +# label, and the mail quota is counted under it. Change it whenever the key +# belongs to another provider account, and only then: renaming the label of +# the same account resets the local quota count. EMAIL_ACCOUNT=default EMAIL_TIMEOUT=10s +# Recipients the configured provider account may be sent per UTC day and per +# UTC calendar month. Empty means the Resend Free plan limits, 100 and 3000, +# for resend and disabled; smtp requires both values. A used-up quota makes +# mail wait for the reset; nothing buys a plan or switches the transport. +EMAIL_QUOTA_DAILY= +EMAIL_QUOTA_MONTHLY= # Public origin for links in mail: https, or http only for a loopback host. APP_PUBLIC_URL=http://localhost:8080 # Read only when EMAIL_PROVIDER=resend, where it is required. Keep the real diff --git a/backend/config/config.go b/backend/config/config.go index b6c8caa..ba66bfa 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -86,6 +86,10 @@ type Config struct { // pinned to. It is configuration identity, never a credential. EmailAccount string EmailTimeout time.Duration + // EmailQuotaDaily and EmailQuotaMonthly limit the recipients sent + // through the configured provider account per UTC day and UTC month. + EmailQuotaDaily int + EmailQuotaMonthly int // AppPublicURL is the public origin without a trailing slash, for links // in mail. AppPublicURL string diff --git a/backend/config/mail.go b/backend/config/mail.go index 144831b..d243dbb 100644 --- a/backend/config/mail.go +++ b/backend/config/mail.go @@ -46,6 +46,16 @@ const ( // delivery worker indefinitely. minEmailTimeout = time.Second maxEmailTimeout = time.Minute + + // The defaults are the Resend Free plan limits checked on 2026-10-05: + // 100 recipients per UTC day and 3000 per month. They apply to resend + // and to disabled, which sends nothing. smtp has no default: a relay's + // limits are not Resend's, so the operator states them. + defaultEmailQuotaDaily = 100 + defaultEmailQuotaMonthly = 3000 + // maxEmailQuota is far above any plan this project can afford; a larger + // value is a typo, not a plan. + maxEmailQuota = 1_000_000_000 ) // emailAccountPattern matches domain.NewMailProviderAccount: a lowercase @@ -73,6 +83,9 @@ func (config *Config) loadMail(lookup LookupEnv) error { if err != nil { return err } + if err := config.loadMailQuota(lookup); err != nil { + return err + } switch config.EmailProvider { case EmailProviderResend: @@ -85,6 +98,35 @@ func (config *Config) loadMail(lookup LookupEnv) error { return nil } +// loadMailQuota reads the quota of the configured provider account. The +// quota is read for every provider, so no transport can run without one. +// For smtp an unset value stays zero, which validation reports as missing. +// +// An empty value counts as unset, as for SMTP_PORT: Compose passes an unset +// variable as an empty string, and a Compose-side default would give smtp +// the Resend limits without the operator stating them. +func (config *Config) loadMailQuota(lookup LookupEnv) error { + daily, monthly := defaultEmailQuotaDaily, defaultEmailQuotaMonthly + if config.EmailProvider == EmailProviderSMTP { + daily, monthly = 0, 0 + } + setOnly := func(key string) (string, bool) { + value, ok := lookup(key) + if strings.TrimSpace(value) == "" { + return "", false + } + return value, ok + } + var err error + if config.EmailQuotaDaily, err = intOrDefault(setOnly, "EMAIL_QUOTA_DAILY", daily); err != nil { + return err + } + if config.EmailQuotaMonthly, err = intOrDefault(setOnly, "EMAIL_QUOTA_MONTHLY", monthly); err != nil { + return err + } + return nil +} + func (config *Config) loadSMTP(lookup LookupEnv) error { config.SMTPHost = strings.TrimSpace(valueOrDefault(lookup, "SMTP_HOST", "")) config.SMTPUsername = strings.TrimSpace(valueOrDefault(lookup, "SMTP_USERNAME", "")) @@ -128,6 +170,9 @@ func (config Config) ValidateMail() error { if config.EmailTimeout < minEmailTimeout || config.EmailTimeout > maxEmailTimeout { return fmt.Errorf("Config.ValidateMail - EMAIL_TIMEOUT must be between %s and %s", minEmailTimeout, maxEmailTimeout) } + if err := config.validateMailQuota(); err != nil { + return err + } switch config.EmailProvider { case EmailProviderResend: @@ -139,6 +184,29 @@ func (config Config) ValidateMail() error { return nil } +// validateMailQuota accepts limits from 1 to maxEmailQuota where the daily +// limit does not exceed the monthly one. There is no value that turns the +// quota off: zero is refused rather than read as "unlimited", so switching +// EMAIL_PROVIDER, for example to smtp, never skips the quota gate. +func (config Config) validateMailQuota() error { + for _, quota := range []struct { + name string + value int + }{{"EMAIL_QUOTA_DAILY", config.EmailQuotaDaily}, {"EMAIL_QUOTA_MONTHLY", config.EmailQuotaMonthly}} { + if quota.value >= 1 && quota.value <= maxEmailQuota { + continue + } + if config.EmailProvider == EmailProviderSMTP { + return fmt.Errorf("Config.validateMailQuota - %s must be set to an integer from 1 to %d when EMAIL_PROVIDER is smtp; the Resend defaults do not apply to a relay", quota.name, maxEmailQuota) + } + return fmt.Errorf("Config.validateMailQuota - %s must be an integer from 1 to %d", quota.name, maxEmailQuota) + } + if config.EmailQuotaDaily > config.EmailQuotaMonthly { + return errors.New("Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY") + } + return nil +} + // validateEmailFrom accepts one RFC 5322 mailbox, with or without a display // name. The address itself follows the account address rules of // domain.NewEmailAddress: ASCII only, because the mailer does not support diff --git a/backend/config/mail_test.go b/backend/config/mail_test.go index 161e088..4efb79f 100644 --- a/backend/config/mail_test.go +++ b/backend/config/mail_test.go @@ -37,6 +37,10 @@ func smtpValues(overrides map[string]string) map[string]string { "SMTP_USERNAME": "mailer", "SMTP_PASSWORD": testSMTPPassword, "SMTP_TLS_MODE": "starttls", + // smtp has no quota default, so a relay always runs with stated + // limits. + "EMAIL_QUOTA_DAILY": "500", + "EMAIL_QUOTA_MONTHLY": "10000", } for key, value := range overrides { values[key] = value @@ -70,6 +74,9 @@ func TestLoadFromEnvMailDisabledIgnoresTransportSettings(t *testing.T) { if settings.EmailAccount != "default" { t.Fatalf("EmailAccount = %q, want the default label", settings.EmailAccount) } + if settings.EmailQuotaDaily != 100 || settings.EmailQuotaMonthly != 3000 { + t.Fatalf("quota = %d/%d, want the Resend Free defaults 100/3000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } if settings.ResendAPIKey != "" || settings.SMTPHost != "" || settings.SMTPPort != 0 || settings.SMTPPassword != "" || settings.SMTPTLSMode != "" { t.Fatal("settings of an inactive transport were loaded") } @@ -92,6 +99,9 @@ func TestLoadFromEnvMailResendLoadsOnlyResendSettings(t *testing.T) { if settings.SMTPHost != "" || settings.SMTPPassword != "" { t.Fatal("SMTP settings were loaded for EMAIL_PROVIDER=resend") } + if settings.EmailQuotaDaily != 100 || settings.EmailQuotaMonthly != 3000 { + t.Fatalf("quota = %d/%d, want the Resend Free defaults 100/3000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } } func TestLoadFromEnvMailSMTPLoadsOnlySMTPSettings(t *testing.T) { @@ -109,6 +119,28 @@ func TestLoadFromEnvMailSMTPLoadsOnlySMTPSettings(t *testing.T) { if settings.ResendAPIKey != "" { t.Fatal("RESEND_API_KEY was loaded for EMAIL_PROVIDER=smtp") } + if settings.EmailQuotaDaily != 500 || settings.EmailQuotaMonthly != 10000 { + t.Fatalf("quota = %d/%d, want the configured 500/10000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } +} + +func TestLoadFromEnvMailQuotaOverridesTheDefaults(t *testing.T) { + // A lowered limit is taken as configured, for every provider. + for _, values := range []map[string]string{ + {"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey}, + smtpValues(nil), + {"EMAIL_PROVIDER": "disabled"}, + } { + values["EMAIL_QUOTA_DAILY"] = " 2 " + values["EMAIL_QUOTA_MONTHLY"] = "5" + settings, err := LoadFromEnv(mailEnvironment(values)) + if err != nil { + t.Fatalf("%s: LoadFromEnv() error = %v", values["EMAIL_PROVIDER"], err) + } + if settings.EmailQuotaDaily != 2 || settings.EmailQuotaMonthly != 5 { + t.Fatalf("%s: quota = %d/%d, want 2/5", values["EMAIL_PROVIDER"], settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } + } } func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) { @@ -128,6 +160,9 @@ func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) { {name: "HTTP loopback IPv6", values: map[string]string{"APP_PUBLIC_URL": "http://[::1]:8080/"}}, {name: "SMTP over STARTTLS", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "STARTTLS"})}, {name: "SMTP host as IP address", values: smtpValues(map[string]string{"SMTP_HOST": "10.0.0.25"})}, + {name: "smallest quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "1", "EMAIL_QUOTA_MONTHLY": "1"}}, + {name: "largest quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "1000000000", "EMAIL_QUOTA_MONTHLY": "1000000000"}}, + {name: "empty quota takes the default", values: map[string]string{"EMAIL_QUOTA_DAILY": " ", "EMAIL_QUOTA_MONTHLY": ""}}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -199,6 +234,15 @@ func TestLoadFromEnvRejectsMailSettings(t *testing.T) { {name: "SMTP password unset", values: smtpValues(nil), unset: []string{"SMTP_PASSWORD"}, want: "Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp"}, {name: "SMTP TLS mode unset", values: smtpValues(nil), unset: []string{"SMTP_TLS_MODE"}, want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls"}, {name: "SMTP plaintext", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "none"}), want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported"}, + {name: "SMTP daily quota unset", values: smtpValues(nil), unset: []string{"EMAIL_QUOTA_DAILY"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be set to an integer from 1 to 1000000000 when EMAIL_PROVIDER is smtp"}, + {name: "SMTP monthly quota unset", values: smtpValues(nil), unset: []string{"EMAIL_QUOTA_MONTHLY"}, want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be set to an integer from 1 to 1000000000 when EMAIL_PROVIDER is smtp"}, + {name: "SMTP quota zero", values: smtpValues(map[string]string{"EMAIL_QUOTA_DAILY": "0"}), want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be set to an integer from 1"}, + {name: "daily quota zero", values: map[string]string{"EMAIL_QUOTA_DAILY": "0"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be an integer from 1 to 1000000000"}, + {name: "daily quota negative", values: map[string]string{"EMAIL_QUOTA_DAILY": "-1"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be an integer from 1"}, + {name: "monthly quota above the maximum", values: map[string]string{"EMAIL_QUOTA_MONTHLY": "1000000001"}, want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be an integer from 1"}, + {name: "daily quota not a number", values: map[string]string{"EMAIL_QUOTA_DAILY": "unlimited"}, want: "config.intOrDefault - EMAIL_QUOTA_DAILY must be an integer"}, + {name: "SMTP quota empty as Compose passes it unset", values: smtpValues(map[string]string{"EMAIL_QUOTA_MONTHLY": ""}), want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be set to an integer from 1"}, + {name: "daily quota above the monthly quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "3001"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/backend/db/migrations/00007_create_mail_quota_usage.sql b/backend/db/migrations/00007_create_mail_quota_usage.sql new file mode 100644 index 0000000..2c573f2 --- /dev/null +++ b/backend/db/migrations/00007_create_mail_quota_usage.sql @@ -0,0 +1,110 @@ +-- +goose Up +-- Mail quota usage: the recipients counted against a provider account per +-- UTC day and per UTC calendar month. The sending path reserves recipients +-- here before it calls the transport, in one transaction that locks the +-- window rows, so concurrent senders never exceed a configured limit +-- together. The limits themselves come from configuration +-- (EMAIL_QUOTA_DAILY, EMAIL_QUOTA_MONTHLY) and are not stored: lowering one +-- takes effect on the next reservation. +-- +-- The table has no foreign key to users or deliveries on purpose. Deleting +-- an account deletes its deliveries and attempts, but the provider still +-- counted the messages already sent, so the usage must stay. The rows hold +-- no personal data: provider and account are configuration labels. +CREATE TABLE mail_quota_usage ( + provider text NOT NULL, + provider_account text NOT NULL, + period_kind text NOT NULL, + -- The UTC date that starts the window: the day itself, or the first day + -- of the month. + period_start date NOT NULL, + used_recipients bigint NOT NULL, + -- Last time the provider itself refused a send for an exhausted quota in + -- this window; NULL when it never did. used_recipients was then raised + -- to the limit, and releases no longer lower it. + provider_exhausted_at timestamptz, + -- Application clock time of the last change. + updated_at timestamptz NOT NULL, + CONSTRAINT mail_quota_usage_pkey PRIMARY KEY ( + provider, provider_account, period_kind, period_start + ), + -- The same label rules as deliveries.provider and + -- deliveries.provider_account. + CONSTRAINT mail_quota_usage_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT mail_quota_usage_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + CONSTRAINT mail_quota_usage_period_kind_known CHECK ( + period_kind IN ('day', 'month') + ), + CONSTRAINT mail_quota_usage_month_starts_on_day_one CHECK ( + period_kind <> 'month' OR extract(DAY FROM period_start) = 1 + ), + CONSTRAINT mail_quota_usage_used_not_negative CHECK (used_recipients >= 0) +); + +-- Mail quota reservations: one row per admitted send, written in the +-- transaction that adds it to mail_quota_usage. The journal makes a release +-- happen at most once per reservation, whatever the caller retries, and lets +-- a retry of the same delivery inside the provider's idempotency window +-- reuse its open reservation instead of counting the message again. +-- +-- Like the usage, it has no foreign key: a reservation outlives its delivery, +-- and delivery_id is an opaque ID without personal data. Every write that +-- also changes mail_quota_usage locks the usage rows first, in +-- (period_kind, period_start) order, and the journal row second. +CREATE TABLE mail_quota_reservations ( + -- Generated in Go. + id uuid NOT NULL, + delivery_id uuid NOT NULL, + provider text NOT NULL, + provider_account text NOT NULL, + -- The windows the recipients were counted in. + day_start date NOT NULL, + month_start date NOT NULL, + recipients bigint NOT NULL, + reserved_at timestamptz NOT NULL, + -- Set once, when the recipients were given back. + released_at timestamptz, + -- The last settled outcome of a send under this reservation; NULL while + -- the send is in flight or its process stopped before settling. + settled_outcome text, + settled_at timestamptz, + CONSTRAINT mail_quota_reservations_pkey PRIMARY KEY (id), + CONSTRAINT mail_quota_reservations_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT mail_quota_reservations_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + CONSTRAINT mail_quota_reservations_windows_match CHECK ( + extract(DAY FROM month_start) = 1 + AND day_start >= month_start + AND day_start < month_start + INTERVAL '1 month' + ), + CONSTRAINT mail_quota_reservations_recipients_positive CHECK ( + recipients > 0 + ), + CONSTRAINT mail_quota_reservations_outcome_known CHECK ( + (settled_outcome IS NULL) = (settled_at IS NULL) + AND ( + settled_outcome IS NULL + OR settled_outcome IN ('accepted', 'unknown', 'rejected', 'not_sent') + ) + ), + CONSTRAINT mail_quota_reservations_times_ordered CHECK ( + (released_at IS NULL OR released_at >= reserved_at) + AND (settled_at IS NULL OR settled_at >= reserved_at) + ) +); + +-- Serves the lookup of an open reservation of a delivery. +CREATE INDEX mail_quota_reservations_open_delivery_idx +ON mail_quota_reservations (delivery_id, reserved_at) +WHERE released_at IS NULL; + +-- +goose Down +DROP TABLE mail_quota_reservations; +DROP TABLE mail_quota_usage; diff --git a/backend/db/queries/delivery.sql b/backend/db/queries/delivery.sql index 756bc42..d6b3c12 100644 --- a/backend/db/queries/delivery.sql +++ b/backend/db/queries/delivery.sql @@ -201,3 +201,21 @@ FOR UPDATE; -- name: DeleteMailRequest :execrows DELETE FROM mail_requests WHERE id = sqlc.arg(id); + +-- Reads the status of the newest delivery of a kind addressed to an account, +-- for the account's own view of its mail. It selects no address and no +-- content. The recipient index narrows the scan to the account's rows. +-- name: GetLatestDeliveryStatus :one +SELECT + id, + kind, + status, + next_attempt_at, + created_at, + updated_at +FROM deliveries +WHERE + recipient_user_id = sqlc.arg(recipient_user_id) + AND kind = sqlc.arg(kind) +ORDER BY created_at DESC, id DESC +LIMIT 1; diff --git a/backend/db/queries/mail_quota.sql b/backend/db/queries/mail_quota.sql new file mode 100644 index 0000000..6d19cae --- /dev/null +++ b/backend/db/queries/mail_quota.sql @@ -0,0 +1,193 @@ +-- Lock order. Every transaction that writes mail_quota_usage first creates +-- and locks all the usage rows it will touch with EnsureMailQuotaRows and +-- LockMailQuotaRows, which both work in (period_kind, period_start) order, +-- and only then writes them or a mail_quota_reservations row. Later UPDATE +-- statements of the same transaction find their rows locked already, so the +-- scan order of an UPDATE never decides the lock order. + +-- Creates the listed window rows of a provider account with no usage when +-- they do not exist yet, in (period_kind, period_start) order. A window key +-- is "/". A concurrent insert of the same row waits +-- for the first transaction and then inserts nothing. Existing rows are +-- neither changed nor locked here. +-- name: EnsureMailQuotaRows :exec +INSERT INTO mail_quota_usage ( + provider, + provider_account, + period_kind, + period_start, + used_recipients, + updated_at +) +SELECT + sqlc.arg(provider)::text, + sqlc.arg(provider_account)::text, + split_part(window_key, '/', 1), + split_part(window_key, '/', 2)::date, + 0, + sqlc.arg(updated_at)::timestamptz +FROM unnest(sqlc.arg(window_keys)::text []) AS window_key +ORDER BY split_part(window_key, '/', 1), split_part(window_key, '/', 2)::date +ON CONFLICT ( + provider, provider_account, period_kind, period_start +) DO NOTHING; + +-- Locks the listed window rows until the transaction ends, in +-- (period_kind, period_start) order, the same order for every caller, and +-- returns their usage. Under READ COMMITTED a waiting caller reads the usage +-- the first caller committed. period_starts narrows the index scan; +-- window_keys selects the exact rows. +-- name: LockMailQuotaRows :many +SELECT + period_kind, + period_start, + used_recipients +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND period_start = any(sqlc.arg(period_starts)::date []) + AND period_kind || '/' || to_char(period_start, 'YYYY-MM-DD') + = any(sqlc.arg(window_keys)::text []) +ORDER BY period_kind, period_start +FOR UPDATE; + +-- Adds recipients to the day and the month row. The caller holds their +-- locks from LockMailQuotaRows and has checked both limits. +-- name: AddMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = mail_quota_usage.used_recipients + + sqlc.arg(recipients)::bigint, + updated_at = sqlc.arg(updated_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Gives back recipients of a released reservation. The caller holds the row +-- locks. A window that the provider reported exhausted keeps its usage: the +-- provider's answer outranks the local count until the window resets. The +-- count never drops below zero. +-- name: ReleaseMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients - sqlc.arg(recipients)::bigint, 0 + ), + updated_at = sqlc.arg(updated_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND provider_exhausted_at IS NULL + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Records that the provider refused a send because the quota of a window is +-- used up: the usage rises to at least the configured limit, so the local +-- gate stops admitting sends until the window resets or an operator raises +-- the limit. The caller holds the row lock. +-- name: MarkMailQuotaExhausted :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients, sqlc.arg(limit_recipients)::bigint + ), + provider_exhausted_at = sqlc.arg(exhausted_at), + updated_at = sqlc.arg(exhausted_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND period_kind = sqlc.arg(period_kind) + AND period_start = sqlc.arg(period_start); + +-- name: InsertMailQuotaReservation :exec +INSERT INTO mail_quota_reservations ( + id, + delivery_id, + provider, + provider_account, + day_start, + month_start, + recipients, + reserved_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(delivery_id), + sqlc.arg(provider), + sqlc.arg(provider_account), + sqlc.arg(day_start), + sqlc.arg(month_start), + sqlc.arg(recipients), + sqlc.arg(reserved_at) +); + +-- Returns the newest open reservation of a delivery under a provider account +-- made at or after reserved_since. A retry of the delivery inside the +-- provider's idempotency window reuses it instead of counting again. +-- name: FindOpenMailQuotaReservation :one +SELECT + id, + day_start, + month_start, + recipients, + reserved_at +FROM mail_quota_reservations +WHERE + delivery_id = sqlc.arg(delivery_id) + AND provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND released_at IS NULL + AND reserved_at >= sqlc.arg(reserved_since) +ORDER BY reserved_at DESC +LIMIT 1; + +-- Marks a reservation released. It matches only an open reservation, so a +-- repeated release changes nothing and returns 0 rows. +-- name: ReleaseMailQuotaReservation :execrows +UPDATE mail_quota_reservations +SET released_at = sqlc.arg(released_at) +WHERE + id = sqlc.arg(id) + AND released_at IS NULL; + +-- Records the latest settled outcome of a send under the reservation. +-- name: RecordMailQuotaOutcome :execrows +UPDATE mail_quota_reservations +SET + settled_outcome = sqlc.arg(settled_outcome), + settled_at = sqlc.arg(settled_at) +WHERE id = sqlc.arg(id); + +-- Reads the usage of the day and the month window without locking. +-- name: GetMailQuotaUsage :many +SELECT + period_kind, + used_recipients, + provider_exhausted_at +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Lists the other accounts of a provider that have usage in a month, so +-- startup can warn about a renamed EMAIL_ACCOUNT. +-- name: ListOtherMailQuotaAccounts :many +SELECT DISTINCT provider_account +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account <> sqlc.arg(provider_account) + AND period_kind = 'month' + AND period_start = sqlc.arg(month_start) + AND used_recipients > 0 +ORDER BY provider_account; diff --git a/backend/integration_test/mail_quota_test.go b/backend/integration_test/mail_quota_test.go new file mode 100644 index 0000000..da3a00e --- /dev/null +++ b/backend/integration_test/mail_quota_test.go @@ -0,0 +1,853 @@ +//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) + } +} diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index ad13b9d..ecd2c93 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -29,15 +29,18 @@ const ( // deliveryMigrationVersion creates deliveryTableNames (mail requests, // deliveries, and their attempts) and deliveryFunctionNames. deliveryMigrationVersion = 6 + // mailQuotaMigrationVersion creates mailQuotaTableNames. + mailQuotaMigrationVersion = 7 ) var ( - // Tables created by 00001, 00002, 00003, 00005, and 00006. - outboxTables = []string{"outbox_events"} - identityTableNames = []string{"users", "email_tokens", "sessions"} - policyTableNames = []string{"policy_versions"} - consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"} - deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"} + // Tables created by 00001, 00002, 00003, 00005, 00006, and 00007. + outboxTables = []string{"outbox_events"} + identityTableNames = []string{"users", "email_tokens", "sessions"} + policyTableNames = []string{"policy_versions"} + consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"} + deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"} + mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"} // Trigger functions created by 00003 and 00006. policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"} deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"} @@ -72,8 +75,9 @@ func TestPostgresMigrations(t *testing.T) { assertTablesExist(ctx, t, pool, true, consumerTableNames...) assertTablesExist(ctx, t, pool, true, deliveryTableNames...) assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...) + assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...) - identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack := false, false, false, false + identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false for rolledBack := 0; ; rolledBack++ { result, err := migrator.DownOne(ctx) if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { @@ -85,6 +89,13 @@ func TestPostgresMigrations(t *testing.T) { if err != nil { t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) } + if result.Version == mailQuotaMigrationVersion { + // The quota migration removes only its counter table; the + // deliveries it does not reference stay. + assertTablesExist(ctx, t, pool, false, mailQuotaTableNames...) + assertTablesExist(ctx, t, pool, true, deliveryTableNames...) + mailQuotaRolledBack = true + } if result.Version == deliveryMigrationVersion { // The delivery migration removes its tables and functions // and leaves the identity tables they referenced. @@ -115,9 +126,9 @@ func TestPostgresMigrations(t *testing.T) { identityRolledBack = true } } - if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack { - t.Fatalf("migrations %d, %d, %d, and %d were not all rolled back", - identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion) + if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack { + t.Fatalf("migrations %d, %d, %d, %d, and %d were not all rolled back", + identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion) } assertTablesExist(ctx, t, pool, false, outboxTables...) assertTablesExist(ctx, t, pool, false, identityTableNames...) diff --git a/backend/internal/adapter/secondary/mail/resend/response.go b/backend/internal/adapter/secondary/mail/resend/response.go index 9a67efd..03fabd3 100644 --- a/backend/internal/adapter/secondary/mail/resend/response.go +++ b/backend/internal/adapter/secondary/mail/resend/response.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -98,9 +99,10 @@ type providerAnswer struct { // have been accepted. Repeating cannot succeed and a new key could send // the message twice: the delivery layer stops and escalates on this code. // - 409 without a known name: unknown, since it may be either of the above. -// - 429 daily_quota_exceeded: quota_exhausted until the next midnight UTC; -// 429 monthly_quota_exceeded: quota_exhausted without a wait hint, the -// reset depends on the billing cycle; other 429: rate_limited with +// - 429 daily_quota_exceeded: quota_exhausted with QuotaPeriod day until +// the next midnight UTC; 429 monthly_quota_exceeded: quota_exhausted +// with QuotaPeriod month and without a wait hint, the reset depends on +// the billing cycle; other 429: rate_limited with // Retry-After or RateLimit-Reset. // - other 4xx (validation, key, permission, not found): invalid_request. // - 503 service_unavailable: rejected temporary; the API refused the @@ -155,9 +157,11 @@ func classifyTooManyRequests(name string, header http.Header, now time.Time) out switch name { case errorNameDailyQuota: // The daily quota resets at midnight UTC, not after a rolling day. - return rejected(outbound.MailRejectionQuotaExhausted, untilNextUTCMidnight(now)) + return quotaExhausted(domain.MailQuotaPeriodDay, untilNextUTCMidnight(now)) case errorNameMonthlyQuota: - return rejected(outbound.MailRejectionQuotaExhausted, 0) + // The monthly reset follows the account's billing cycle, which the + // API does not report. + return quotaExhausted(domain.MailQuotaPeriodMonth, 0) default: return rejected(outbound.MailRejectionRateLimited, rateLimitWait(header, now)) } @@ -167,6 +171,12 @@ func rejected(reason outbound.MailRejection, wait time.Duration) outbound.SendRe return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait} } +func quotaExhausted(period domain.MailQuotaPeriod, wait time.Duration) outbound.SendResult { + result := rejected(outbound.MailRejectionQuotaExhausted, wait) + result.QuotaPeriod = period + return result +} + func unknownResult(wait time.Duration) outbound.SendResult { return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait} } diff --git a/backend/internal/adapter/secondary/mail/resend/sender.go b/backend/internal/adapter/secondary/mail/resend/sender.go index ee19879..9e08453 100644 --- a/backend/internal/adapter/secondary/mail/resend/sender.go +++ b/backend/internal/adapter/secondary/mail/resend/sender.go @@ -65,6 +65,13 @@ type Sender struct { const redactionMarker = "[redacted Resend API key]" +// IdempotencyWindow is how long Resend keeps an Idempotency-Key and answers +// a repeated request under it with the original result instead of sending +// again: 24 hours, per the Resend API documentation. Bootstrap passes it to +// notification.NewQuotaGate, so a retry inside the window does not count +// against the quota a second time. +const IdempotencyWindow = 24 * time.Hour + // credential holds the Authorization header value. It redacts itself in fmt // and slog output in case it is ever printed directly. type credential struct { diff --git a/backend/internal/adapter/secondary/mail/resend/sender_test.go b/backend/internal/adapter/secondary/mail/resend/sender_test.go index e3fe0be..f5e683b 100644 --- a/backend/internal/adapter/secondary/mail/resend/sender_test.go +++ b/backend/internal/adapter/secondary/mail/resend/sender_test.go @@ -213,6 +213,13 @@ func TestSendClassifiesProviderAnswers(t *testing.T) { rejectedAs := func(reason outbound.MailRejection, wait time.Duration, code outbound.MailProviderCode) outbound.SendResult { return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait, ProviderCode: code} } + // quotaAs names the window, so the quota gate need not guess it from + // the wait. + quotaAs := func(period domain.MailQuotaPeriod, wait time.Duration, code outbound.MailProviderCode) outbound.SendResult { + result := rejectedAs(outbound.MailRejectionQuotaExhausted, wait, code) + result.QuotaPeriod = period + return result + } unknown := outbound.SendResult{Outcome: outbound.MailOutcomeUnknown} unknownAs := func(wait time.Duration, code outbound.MailProviderCode) outbound.SendResult { return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait, ProviderCode: code} @@ -243,8 +250,8 @@ func TestSendClassifiesProviderAnswers(t *testing.T) { {name: "429 rate limit with an HTTP date", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": fixedNow.Add(90 * time.Second).Format(http.TimeFormat)}), want: rejectedAs(outbound.MailRejectionRateLimited, 90*time.Second, "rate_limit_exceeded")}, {name: "429 rate limit with a huge Retry-After", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": "99999999999"}), want: rejectedAs(outbound.MailRejectionRateLimited, 24*time.Hour, "rate_limit_exceeded")}, {name: "429 without a body", respond: respondJSON(http.StatusTooManyRequests, ``, nil), want: rejectedAs(outbound.MailRejectionRateLimited, 0, "")}, - {name: "429 daily quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "daily_quota_exceeded"), map[string]string{"Retry-After": "1"}), want: rejectedAs(outbound.MailRejectionQuotaExhausted, 150*time.Minute, "daily_quota_exceeded")}, - {name: "429 monthly quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "monthly_quota_exceeded"), nil), want: rejectedAs(outbound.MailRejectionQuotaExhausted, 0, "monthly_quota_exceeded")}, + {name: "429 daily quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "daily_quota_exceeded"), map[string]string{"Retry-After": "1"}), want: quotaAs(domain.MailQuotaPeriodDay, 150*time.Minute, "daily_quota_exceeded")}, + {name: "429 monthly quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "monthly_quota_exceeded"), nil), want: quotaAs(domain.MailQuotaPeriodMonth, 0, "monthly_quota_exceeded")}, {name: "500 application error", respond: respondJSON(http.StatusInternalServerError, providerError(500, "application_error"), map[string]string{"Retry-After": "5"}), want: unknownAs(0, "application_error")}, {name: "503 service unavailable", respond: respondJSON(http.StatusServiceUnavailable, providerError(503, "service_unavailable"), map[string]string{"Retry-After": "30"}), want: rejectedAs(outbound.MailRejectionTemporary, 30*time.Second, "service_unavailable")}, {name: "401 invalid API key", respond: respondJSON(http.StatusUnauthorized, providerError(401, "invalid_api_key"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "invalid_api_key")}, diff --git a/backend/internal/adapter/secondary/postgres/delivery.go b/backend/internal/adapter/secondary/postgres/delivery.go index 8ee123c..582f9a8 100644 --- a/backend/internal/adapter/secondary/postgres/delivery.go +++ b/backend/internal/adapter/secondary/postgres/delivery.go @@ -154,6 +154,36 @@ func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.U return attempts, nil } +func (repository deliveryRepository) LatestForRecipient(ctx context.Context, recipientUserID uuid.UUID, kind domain.MailKind) (outbound.DeliveryStatusSnapshot, error) { + const location = "deliveryRepository.LatestForRecipient" + row, err := repository.queries.GetLatestDeliveryStatus(ctx, sqlc.GetLatestDeliveryStatusParams{ + RecipientUserID: pgUUID(recipientUserID), + Kind: string(kind), + }) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - select delivery status: %w", location, outbound.ErrDeliveryNotFound) + } + if err != nil { + return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - select delivery status: %w", location, mapDeliveryError(err)) + } + storedKind, err := domain.ParseMailKind(row.Kind) + if err != nil { + return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - decode kind: %w", location, err) + } + status, err := domain.ParseDeliveryStatus(row.Status) + if err != nil { + return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - decode status: %w", location, err) + } + return outbound.DeliveryStatusSnapshot{ + DeliveryID: uuid.UUID(row.ID.Bytes), + Kind: storedKind, + Status: status, + NextAttemptAt: zeroableTime(row.NextAttemptAt), + CreatedAt: row.CreatedAt.Time, + UpdatedAt: row.UpdatedAt.Time, + }, nil +} + func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error { const location = "deliveryRepository.RecordAttempt" if next.IsZero() || attempt.DeliveryID != next.ID() || attempt.Number != next.AttemptCount() || next.Version() <= 1 { diff --git a/backend/internal/adapter/secondary/postgres/mail_quota.go b/backend/internal/adapter/secondary/postgres/mail_quota.go new file mode 100644 index 0000000..ba1f068 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/mail_quota.go @@ -0,0 +1,369 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "slices" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// quotaDateLayout is the period_start part of a window key; the queries +// format period_start with the same layout (to_char 'YYYY-MM-DD'). +const quotaDateLayout = time.DateOnly + +// MailQuotaStore reads quota usage outside a transaction, for the startup +// report, operators, and metrics. Writes need a transaction and go through +// UnitOfWork.MailQuotas. +type MailQuotaStore struct { + queries *sqlc.Queries +} + +func NewMailQuotaStore(pool *pgxpool.Pool) *MailQuotaStore { + return &MailQuotaStore{queries: sqlc.New(standaloneDB{pool: pool})} +} + +func (store *MailQuotaStore) MailQuotas() outbound.MailQuotaUsageReader { + return mailQuotaRepository{queries: store.queries} +} + +// MailQuotas is available for writes only inside a transaction: the writes +// lock window rows until the transaction ends. +func (unit *UnitOfWork) MailQuotas() outbound.MailQuotaRepository { + return mailQuotaRepository{queries: unit.queries} +} + +type mailQuotaRepository struct { + queries *sqlc.Queries +} + +var _ outbound.MailQuotaRepository = mailQuotaRepository{} + +// quotaWindow is one usage row of an account. +type quotaWindow struct { + period domain.MailQuotaPeriod + start time.Time +} + +func (window quotaWindow) key() string { + return string(window.period) + "/" + window.start.UTC().Format(quotaDateLayout) +} + +// lockWindows creates the missing rows and locks every listed row of the +// account in (period_kind, period_start) order with one statement. All quota +// writes call it first with the full set of rows they will touch, and later +// UPDATE statements find their rows locked already, so the lock order never +// depends on a query plan and two quota writers wait for each other on +// these rows in one direction only. Rows of other tables that a caller +// locks in the same transaction, such as the delivery, are outside this +// rule; the caller keeps its own order for them. +func (repository mailQuotaRepository) lockWindows( + ctx context.Context, + location string, + account domain.MailProviderAccount, + windows []quotaWindow, + at time.Time, +) ([]sqlc.LockMailQuotaRowsRow, error) { + keys := make([]string, 0, len(windows)) + starts := make([]pgtype.Date, 0, len(windows)) + for _, window := range windows { + if !slices.Contains(keys, window.key()) { + keys = append(keys, window.key()) + starts = append(starts, pgDate(window.start)) + } + } + err := repository.queries.EnsureMailQuotaRows(ctx, sqlc.EnsureMailQuotaRowsParams{ + Provider: account.Provider(), + ProviderAccount: account.Account(), + UpdatedAt: pgTime(at), + WindowKeys: keys, + }) + if err != nil { + return nil, fmt.Errorf("%s - create window rows: %w", location, mapDeliveryError(err)) + } + rows, err := repository.queries.LockMailQuotaRows(ctx, sqlc.LockMailQuotaRowsParams{ + Provider: account.Provider(), + ProviderAccount: account.Account(), + PeriodStarts: starts, + WindowKeys: keys, + }) + if err != nil { + return nil, fmt.Errorf("%s - lock window rows: %w", location, mapDeliveryError(err)) + } + if len(rows) != len(keys) { + return nil, fmt.Errorf("%s - locked %d window rows, want %d", location, len(rows), len(keys)) + } + return rows, nil +} + +func reservationWindows(reservation outbound.MailQuotaReservation) []quotaWindow { + return []quotaWindow{ + {period: domain.MailQuotaPeriodDay, start: reservation.Windows.DayStart()}, + {period: domain.MailQuotaPeriodMonth, start: reservation.Windows.MonthStart()}, + } +} + +// Reserve looks for a reusable reservation without locks first: the journal +// rows of one delivery are written only by that delivery's single in-flight +// send. A new reservation locks both window rows, checks both limits against +// the committed usage, and adds the recipients and the journal row together. +func (repository mailQuotaRepository) Reserve(ctx context.Context, request outbound.MailQuotaReserveRequest) (outbound.MailQuotaReserveResult, error) { + const location = "mailQuotaRepository.Reserve" + reservation := request.Reservation + if err := checkQuotaReservation(location, reservation); err != nil { + return outbound.MailQuotaReserveResult{}, err + } + if request.Limits.IsZero() { + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - limits were not built by domain.NewMailQuotaLimits: %w", location, domain.ErrInvalidMailQuota) + } + if !request.ReuseSince.IsZero() { + reused, found, err := repository.findOpen(ctx, reservation, request.ReuseSince) + if err != nil { + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - %w", location, err) + } + if found { + return outbound.MailQuotaReserveResult{Reservation: reused, Reused: true}, nil + } + } + + rows, err := repository.lockWindows(ctx, location, reservation.Account, reservationWindows(reservation), reservation.ReservedAt) + if err != nil { + return outbound.MailQuotaReserveResult{}, err + } + var check outbound.MailQuotaCheck + for _, row := range rows { + period := domain.MailQuotaPeriod(row.PeriodKind) + // Written as a subtraction so that no sum can overflow. + exceeded := row.UsedRecipients > request.Limits.Of(period)-reservation.Recipients + switch period { + case domain.MailQuotaPeriodDay: + check.DayExceeded = exceeded + case domain.MailQuotaPeriodMonth: + check.MonthExceeded = exceeded + default: + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - unknown period kind %q", location, row.PeriodKind) + } + } + if !check.Reserved() { + return outbound.MailQuotaReserveResult{Check: check}, nil + } + key := quotaKeyOf(reservation) + updated, err := repository.queries.AddMailQuotaUsage(ctx, sqlc.AddMailQuotaUsageParams{ + Recipients: reservation.Recipients, + UpdatedAt: pgTime(reservation.ReservedAt), + Provider: key.provider, + ProviderAccount: key.account, + DayStart: key.dayStart, + MonthStart: key.monthStart, + }) + if err != nil { + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - add usage: %w", location, mapDeliveryError(err)) + } + if updated != int64(len(rows)) { + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - updated %d window rows, want %d", location, updated, len(rows)) + } + err = repository.queries.InsertMailQuotaReservation(ctx, sqlc.InsertMailQuotaReservationParams{ + ID: pgUUID(reservation.ID), + DeliveryID: pgUUID(reservation.DeliveryID), + Provider: key.provider, + ProviderAccount: key.account, + DayStart: key.dayStart, + MonthStart: key.monthStart, + Recipients: reservation.Recipients, + ReservedAt: pgTime(reservation.ReservedAt), + }) + if err != nil { + return outbound.MailQuotaReserveResult{}, fmt.Errorf("%s - journal reservation: %w", location, mapDeliveryError(err)) + } + return outbound.MailQuotaReserveResult{Check: check, Reservation: reservation}, nil +} + +func (repository mailQuotaRepository) findOpen( + ctx context.Context, + reservation outbound.MailQuotaReservation, + since time.Time, +) (outbound.MailQuotaReservation, bool, error) { + row, err := repository.queries.FindOpenMailQuotaReservation(ctx, sqlc.FindOpenMailQuotaReservationParams{ + DeliveryID: pgUUID(reservation.DeliveryID), + Provider: reservation.Account.Provider(), + ProviderAccount: reservation.Account.Account(), + ReservedSince: pgTime(since), + }) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.MailQuotaReservation{}, false, nil + } + if err != nil { + return outbound.MailQuotaReservation{}, false, fmt.Errorf("find open reservation: %w", mapDeliveryError(err)) + } + windows := domain.MailQuotaWindowsAt(utcDate(row.DayStart)) + if !windows.MonthStart().Equal(utcDate(row.MonthStart)) { + return outbound.MailQuotaReservation{}, false, fmt.Errorf("stored reservation windows do not match: %w", domain.ErrInvalidMailQuota) + } + return outbound.MailQuotaReservation{ + ID: uuid.UUID(row.ID.Bytes), + DeliveryID: reservation.DeliveryID, + Account: reservation.Account, + Windows: windows, + Recipients: row.Recipients, + ReservedAt: row.ReservedAt.Time, + }, true, nil +} + +// Settle locks the reservation's windows and the exhausted window together, +// then writes the journal and the usage. The journal update by ID makes the +// release happen at most once. +func (repository mailQuotaRepository) Settle(ctx context.Context, settlement outbound.MailQuotaSettlement) (bool, error) { + const location = "mailQuotaRepository.Settle" + reservation := settlement.Reservation + if err := checkQuotaReservation(location, reservation); err != nil { + return false, err + } + windows := reservationWindows(reservation) + var exhausted quotaWindow + if settlement.ExhaustedPeriod != "" { + exhausted = quotaWindow{period: settlement.ExhaustedPeriod, start: settlement.ExhaustedWindows.Start(settlement.ExhaustedPeriod)} + if exhausted.start.IsZero() || settlement.ExhaustedLimit <= 0 { + return false, fmt.Errorf("%s - an exhausted window needs a known period, windows, and a positive limit: %w", location, domain.ErrInvalidMailQuota) + } + windows = append(windows, exhausted) + } + if _, err := repository.lockWindows(ctx, location, reservation.Account, windows, settlement.At); err != nil { + return false, err + } + key := quotaKeyOf(reservation) + released := false + if settlement.Release { + opened, err := repository.queries.ReleaseMailQuotaReservation(ctx, sqlc.ReleaseMailQuotaReservationParams{ + ReleasedAt: pgTime(settlement.At), + ID: pgUUID(reservation.ID), + }) + if err != nil { + return false, fmt.Errorf("%s - release journal row: %w", location, mapDeliveryError(err)) + } + if opened == 1 { + _, err := repository.queries.ReleaseMailQuotaUsage(ctx, sqlc.ReleaseMailQuotaUsageParams{ + Recipients: reservation.Recipients, + UpdatedAt: pgTime(settlement.At), + Provider: key.provider, + ProviderAccount: key.account, + DayStart: key.dayStart, + MonthStart: key.monthStart, + }) + if err != nil { + return false, fmt.Errorf("%s - release usage: %w", location, mapDeliveryError(err)) + } + released = true + } + } + recorded, err := repository.queries.RecordMailQuotaOutcome(ctx, sqlc.RecordMailQuotaOutcomeParams{ + SettledOutcome: pgOptionalText(string(settlement.Outcome)), + SettledAt: pgTime(settlement.At), + ID: pgUUID(reservation.ID), + }) + if err != nil { + return false, fmt.Errorf("%s - record outcome: %w", location, mapDeliveryError(err)) + } + if recorded != 1 { + return false, fmt.Errorf("%s - reservation %s is not journaled: %w", location, reservation.ID, domain.ErrInvalidMailQuota) + } + if settlement.ExhaustedPeriod != "" { + _, err := repository.queries.MarkMailQuotaExhausted(ctx, sqlc.MarkMailQuotaExhaustedParams{ + LimitRecipients: settlement.ExhaustedLimit, + ExhaustedAt: pgTime(settlement.At), + Provider: key.provider, + ProviderAccount: key.account, + PeriodKind: string(exhausted.period), + PeriodStart: pgDate(exhausted.start), + }) + if err != nil { + return false, fmt.Errorf("%s - mark the window exhausted: %w", location, mapDeliveryError(err)) + } + } + return released, nil +} + +func (repository mailQuotaRepository) Usage(ctx context.Context, account domain.MailProviderAccount, windows domain.MailQuotaWindows) (outbound.MailQuotaUsage, error) { + const location = "mailQuotaRepository.Usage" + if account.IsZero() || windows.IsZero() { + return outbound.MailQuotaUsage{}, fmt.Errorf("%s - account and windows are required: %w", location, domain.ErrInvalidMailQuota) + } + rows, err := repository.queries.GetMailQuotaUsage(ctx, sqlc.GetMailQuotaUsageParams{ + Provider: account.Provider(), + ProviderAccount: account.Account(), + DayStart: pgDate(windows.DayStart()), + MonthStart: pgDate(windows.MonthStart()), + }) + if err != nil { + return outbound.MailQuotaUsage{}, fmt.Errorf("%s - select usage: %w", location, mapDeliveryError(err)) + } + var usage outbound.MailQuotaUsage + for _, row := range rows { + switch domain.MailQuotaPeriod(row.PeriodKind) { + case domain.MailQuotaPeriodDay: + usage.DayUsed, usage.DayProviderExhaustedAt = row.UsedRecipients, zeroableTime(row.ProviderExhaustedAt) + case domain.MailQuotaPeriodMonth: + usage.MonthUsed, usage.MonthProviderExhaustedAt = row.UsedRecipients, zeroableTime(row.ProviderExhaustedAt) + } + } + return usage, nil +} + +func (repository mailQuotaRepository) OtherAccountsWithUsage(ctx context.Context, account domain.MailProviderAccount, monthStart time.Time) ([]string, error) { + const location = "mailQuotaRepository.OtherAccountsWithUsage" + if account.IsZero() || monthStart.IsZero() { + return nil, fmt.Errorf("%s - account and month are required: %w", location, domain.ErrInvalidMailQuota) + } + accounts, err := repository.queries.ListOtherMailQuotaAccounts(ctx, sqlc.ListOtherMailQuotaAccountsParams{ + Provider: account.Provider(), + ProviderAccount: account.Account(), + MonthStart: pgDate(monthStart), + }) + if err != nil { + return nil, fmt.Errorf("%s - select accounts: %w", location, mapDeliveryError(err)) + } + return accounts, nil +} + +func checkQuotaReservation(location string, reservation outbound.MailQuotaReservation) error { + switch { + case reservation.ID == uuid.Nil || reservation.DeliveryID == uuid.Nil: + return fmt.Errorf("%s - reservation and delivery IDs are required: %w", location, domain.ErrInvalidMailQuota) + case reservation.Account.IsZero() || reservation.Windows.IsZero() || reservation.Recipients <= 0 || reservation.ReservedAt.IsZero(): + return fmt.Errorf("%s - reservation needs an account, windows, a positive recipient count, and a time: %w", location, domain.ErrInvalidMailQuota) + } + return nil +} + +type quotaKey struct { + provider, account string + dayStart, monthStart pgtype.Date +} + +func quotaKeyOf(reservation outbound.MailQuotaReservation) quotaKey { + return quotaKey{ + provider: reservation.Account.Provider(), + account: reservation.Account.Account(), + dayStart: pgDate(reservation.Windows.DayStart()), + monthStart: pgDate(reservation.Windows.MonthStart()), + } +} + +// pgDate stores the UTC calendar date of a window start; the windows are +// built in UTC, so the date never shifts with the session time zone. +func pgDate(value time.Time) pgtype.Date { + return pgtype.Date{Time: value.UTC(), Valid: true} +} + +// utcDate reads a stored date as 00:00 UTC of that day. +func utcDate(value pgtype.Date) time.Time { + return time.Date(value.Time.Year(), value.Time.Month(), value.Time.Day(), 0, 0, 0, 0, time.UTC) +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go index 5224a0b..fa5ab0f 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go @@ -80,6 +80,53 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery return i, err } +const getLatestDeliveryStatus = `-- name: GetLatestDeliveryStatus :one +SELECT + id, + kind, + status, + next_attempt_at, + created_at, + updated_at +FROM deliveries +WHERE + recipient_user_id = $1 + AND kind = $2 +ORDER BY created_at DESC, id DESC +LIMIT 1 +` + +type GetLatestDeliveryStatusParams struct { + RecipientUserID pgtype.UUID + Kind string +} + +type GetLatestDeliveryStatusRow struct { + ID pgtype.UUID + Kind string + Status string + NextAttemptAt pgtype.Timestamptz + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +// Reads the status of the newest delivery of a kind addressed to an account, +// for the account's own view of its mail. It selects no address and no +// content. The recipient index narrows the scan to the account's rows. +func (q *Queries) GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error) { + row := q.db.QueryRow(ctx, getLatestDeliveryStatus, arg.RecipientUserID, arg.Kind) + var i GetLatestDeliveryStatusRow + err := row.Scan( + &i.ID, + &i.Kind, + &i.Status, + &i.NextAttemptAt, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + const insertDelivery = `-- name: InsertDelivery :execrows INSERT INTO deliveries ( id, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/mail_quota.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/mail_quota.sql.go new file mode 100644 index 0000000..0f63cd5 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/mail_quota.sql.go @@ -0,0 +1,493 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: mail_quota.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const addMailQuotaUsage = `-- name: AddMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = mail_quota_usage.used_recipients + + $1::bigint, + updated_at = $2 +WHERE + provider = $3 + AND provider_account = $4 + AND ( + (period_kind = 'day' AND period_start = $5) + OR (period_kind = 'month' AND period_start = $6) + ) +` + +type AddMailQuotaUsageParams struct { + Recipients int64 + UpdatedAt pgtype.Timestamptz + Provider string + ProviderAccount string + DayStart pgtype.Date + MonthStart pgtype.Date +} + +// Adds recipients to the day and the month row. The caller holds their +// locks from LockMailQuotaRows and has checked both limits. +func (q *Queries) AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error) { + result, err := q.db.Exec(ctx, addMailQuotaUsage, + arg.Recipients, + arg.UpdatedAt, + arg.Provider, + arg.ProviderAccount, + arg.DayStart, + arg.MonthStart, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const ensureMailQuotaRows = `-- name: EnsureMailQuotaRows :exec + +INSERT INTO mail_quota_usage ( + provider, + provider_account, + period_kind, + period_start, + used_recipients, + updated_at +) +SELECT + $1::text, + $2::text, + split_part(window_key, '/', 1), + split_part(window_key, '/', 2)::date, + 0, + $3::timestamptz +FROM unnest($4::text []) AS window_key +ORDER BY split_part(window_key, '/', 1), split_part(window_key, '/', 2)::date +ON CONFLICT ( + provider, provider_account, period_kind, period_start +) DO NOTHING +` + +type EnsureMailQuotaRowsParams struct { + Provider string + ProviderAccount string + UpdatedAt pgtype.Timestamptz + WindowKeys []string +} + +// Lock order. Every transaction that writes mail_quota_usage first creates +// and locks all the usage rows it will touch with EnsureMailQuotaRows and +// LockMailQuotaRows, which both work in (period_kind, period_start) order, +// and only then writes them or a mail_quota_reservations row. Later UPDATE +// statements of the same transaction find their rows locked already, so the +// scan order of an UPDATE never decides the lock order. +// Creates the listed window rows of a provider account with no usage when +// they do not exist yet, in (period_kind, period_start) order. A window key +// is "/". A concurrent insert of the same row waits +// for the first transaction and then inserts nothing. Existing rows are +// neither changed nor locked here. +func (q *Queries) EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error { + _, err := q.db.Exec(ctx, ensureMailQuotaRows, + arg.Provider, + arg.ProviderAccount, + arg.UpdatedAt, + arg.WindowKeys, + ) + return err +} + +const findOpenMailQuotaReservation = `-- name: FindOpenMailQuotaReservation :one +SELECT + id, + day_start, + month_start, + recipients, + reserved_at +FROM mail_quota_reservations +WHERE + delivery_id = $1 + AND provider = $2 + AND provider_account = $3 + AND released_at IS NULL + AND reserved_at >= $4 +ORDER BY reserved_at DESC +LIMIT 1 +` + +type FindOpenMailQuotaReservationParams struct { + DeliveryID pgtype.UUID + Provider string + ProviderAccount string + ReservedSince pgtype.Timestamptz +} + +type FindOpenMailQuotaReservationRow struct { + ID pgtype.UUID + DayStart pgtype.Date + MonthStart pgtype.Date + Recipients int64 + ReservedAt pgtype.Timestamptz +} + +// Returns the newest open reservation of a delivery under a provider account +// made at or after reserved_since. A retry of the delivery inside the +// provider's idempotency window reuses it instead of counting again. +func (q *Queries) FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error) { + row := q.db.QueryRow(ctx, findOpenMailQuotaReservation, + arg.DeliveryID, + arg.Provider, + arg.ProviderAccount, + arg.ReservedSince, + ) + var i FindOpenMailQuotaReservationRow + err := row.Scan( + &i.ID, + &i.DayStart, + &i.MonthStart, + &i.Recipients, + &i.ReservedAt, + ) + return i, err +} + +const getMailQuotaUsage = `-- name: GetMailQuotaUsage :many +SELECT + period_kind, + used_recipients, + provider_exhausted_at +FROM mail_quota_usage +WHERE + provider = $1 + AND provider_account = $2 + AND ( + (period_kind = 'day' AND period_start = $3) + OR (period_kind = 'month' AND period_start = $4) + ) +` + +type GetMailQuotaUsageParams struct { + Provider string + ProviderAccount string + DayStart pgtype.Date + MonthStart pgtype.Date +} + +type GetMailQuotaUsageRow struct { + PeriodKind string + UsedRecipients int64 + ProviderExhaustedAt pgtype.Timestamptz +} + +// Reads the usage of the day and the month window without locking. +func (q *Queries) GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error) { + rows, err := q.db.Query(ctx, getMailQuotaUsage, + arg.Provider, + arg.ProviderAccount, + arg.DayStart, + arg.MonthStart, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetMailQuotaUsageRow + for rows.Next() { + var i GetMailQuotaUsageRow + if err := rows.Scan(&i.PeriodKind, &i.UsedRecipients, &i.ProviderExhaustedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const insertMailQuotaReservation = `-- name: InsertMailQuotaReservation :exec +INSERT INTO mail_quota_reservations ( + id, + delivery_id, + provider, + provider_account, + day_start, + month_start, + recipients, + reserved_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8 +) +` + +type InsertMailQuotaReservationParams struct { + ID pgtype.UUID + DeliveryID pgtype.UUID + Provider string + ProviderAccount string + DayStart pgtype.Date + MonthStart pgtype.Date + Recipients int64 + ReservedAt pgtype.Timestamptz +} + +func (q *Queries) InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error { + _, err := q.db.Exec(ctx, insertMailQuotaReservation, + arg.ID, + arg.DeliveryID, + arg.Provider, + arg.ProviderAccount, + arg.DayStart, + arg.MonthStart, + arg.Recipients, + arg.ReservedAt, + ) + return err +} + +const listOtherMailQuotaAccounts = `-- name: ListOtherMailQuotaAccounts :many +SELECT DISTINCT provider_account +FROM mail_quota_usage +WHERE + provider = $1 + AND provider_account <> $2 + AND period_kind = 'month' + AND period_start = $3 + AND used_recipients > 0 +ORDER BY provider_account +` + +type ListOtherMailQuotaAccountsParams struct { + Provider string + ProviderAccount string + MonthStart pgtype.Date +} + +// Lists the other accounts of a provider that have usage in a month, so +// startup can warn about a renamed EMAIL_ACCOUNT. +func (q *Queries) ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error) { + rows, err := q.db.Query(ctx, listOtherMailQuotaAccounts, arg.Provider, arg.ProviderAccount, arg.MonthStart) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var provider_account string + if err := rows.Scan(&provider_account); err != nil { + return nil, err + } + items = append(items, provider_account) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockMailQuotaRows = `-- name: LockMailQuotaRows :many +SELECT + period_kind, + period_start, + used_recipients +FROM mail_quota_usage +WHERE + provider = $1 + AND provider_account = $2 + AND period_start = any($3::date []) + AND period_kind || '/' || to_char(period_start, 'YYYY-MM-DD') + = any($4::text []) +ORDER BY period_kind, period_start +FOR UPDATE +` + +type LockMailQuotaRowsParams struct { + Provider string + ProviderAccount string + PeriodStarts []pgtype.Date + WindowKeys []string +} + +type LockMailQuotaRowsRow struct { + PeriodKind string + PeriodStart pgtype.Date + UsedRecipients int64 +} + +// Locks the listed window rows until the transaction ends, in +// (period_kind, period_start) order, the same order for every caller, and +// returns their usage. Under READ COMMITTED a waiting caller reads the usage +// the first caller committed. period_starts narrows the index scan; +// window_keys selects the exact rows. +func (q *Queries) LockMailQuotaRows(ctx context.Context, arg LockMailQuotaRowsParams) ([]LockMailQuotaRowsRow, error) { + rows, err := q.db.Query(ctx, lockMailQuotaRows, + arg.Provider, + arg.ProviderAccount, + arg.PeriodStarts, + arg.WindowKeys, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []LockMailQuotaRowsRow + for rows.Next() { + var i LockMailQuotaRowsRow + if err := rows.Scan(&i.PeriodKind, &i.PeriodStart, &i.UsedRecipients); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const markMailQuotaExhausted = `-- name: MarkMailQuotaExhausted :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients, $1::bigint + ), + provider_exhausted_at = $2, + updated_at = $2 +WHERE + provider = $3 + AND provider_account = $4 + AND period_kind = $5 + AND period_start = $6 +` + +type MarkMailQuotaExhaustedParams struct { + LimitRecipients int64 + ExhaustedAt pgtype.Timestamptz + Provider string + ProviderAccount string + PeriodKind string + PeriodStart pgtype.Date +} + +// Records that the provider refused a send because the quota of a window is +// used up: the usage rises to at least the configured limit, so the local +// gate stops admitting sends until the window resets or an operator raises +// the limit. The caller holds the row lock. +func (q *Queries) MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error) { + result, err := q.db.Exec(ctx, markMailQuotaExhausted, + arg.LimitRecipients, + arg.ExhaustedAt, + arg.Provider, + arg.ProviderAccount, + arg.PeriodKind, + arg.PeriodStart, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const recordMailQuotaOutcome = `-- name: RecordMailQuotaOutcome :execrows +UPDATE mail_quota_reservations +SET + settled_outcome = $1, + settled_at = $2 +WHERE id = $3 +` + +type RecordMailQuotaOutcomeParams struct { + SettledOutcome pgtype.Text + SettledAt pgtype.Timestamptz + ID pgtype.UUID +} + +// Records the latest settled outcome of a send under the reservation. +func (q *Queries) RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error) { + result, err := q.db.Exec(ctx, recordMailQuotaOutcome, arg.SettledOutcome, arg.SettledAt, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const releaseMailQuotaReservation = `-- name: ReleaseMailQuotaReservation :execrows +UPDATE mail_quota_reservations +SET released_at = $1 +WHERE + id = $2 + AND released_at IS NULL +` + +type ReleaseMailQuotaReservationParams struct { + ReleasedAt pgtype.Timestamptz + ID pgtype.UUID +} + +// Marks a reservation released. It matches only an open reservation, so a +// repeated release changes nothing and returns 0 rows. +func (q *Queries) ReleaseMailQuotaReservation(ctx context.Context, arg ReleaseMailQuotaReservationParams) (int64, error) { + result, err := q.db.Exec(ctx, releaseMailQuotaReservation, arg.ReleasedAt, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const releaseMailQuotaUsage = `-- name: ReleaseMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients - $1::bigint, 0 + ), + updated_at = $2 +WHERE + provider = $3 + AND provider_account = $4 + AND provider_exhausted_at IS NULL + AND ( + (period_kind = 'day' AND period_start = $5) + OR (period_kind = 'month' AND period_start = $6) + ) +` + +type ReleaseMailQuotaUsageParams struct { + Recipients int64 + UpdatedAt pgtype.Timestamptz + Provider string + ProviderAccount string + DayStart pgtype.Date + MonthStart pgtype.Date +} + +// Gives back recipients of a released reservation. The caller holds the row +// locks. A window that the provider reported exhausted keeps its usage: the +// provider's answer outranks the local count until the window resets. The +// count never drops below zero. +func (q *Queries) ReleaseMailQuotaUsage(ctx context.Context, arg ReleaseMailQuotaUsageParams) (int64, error) { + result, err := q.db.Exec(ctx, releaseMailQuotaUsage, + arg.Recipients, + arg.UpdatedAt, + arg.Provider, + arg.ProviderAccount, + arg.DayStart, + arg.MonthStart, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 1e67074..2ea1836 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -79,6 +79,30 @@ type EmailToken struct { InvalidatedAt pgtype.Timestamptz } +type MailQuotaReservation struct { + ID pgtype.UUID + DeliveryID pgtype.UUID + Provider string + ProviderAccount string + DayStart pgtype.Date + MonthStart pgtype.Date + Recipients int64 + ReservedAt pgtype.Timestamptz + ReleasedAt pgtype.Timestamptz + SettledOutcome pgtype.Text + SettledAt pgtype.Timestamptz +} + +type MailQuotaUsage struct { + Provider string + ProviderAccount string + PeriodKind string + PeriodStart pgtype.Date + UsedRecipients int64 + ProviderExhaustedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + type MailRequest struct { ID pgtype.UUID RecipientUserID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 9488935..58483a4 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -11,6 +11,9 @@ import ( ) type Querier interface { + // Adds recipients to the day and the month row. The caller holds their + // locks from LockMailQuotaRows and has checked both limits. + AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error) // Consumes a token in one statement. Concurrent callers queue on the token // row lock; under READ COMMITTED each waiter re-checks the WHERE clause // against the committed row, so exactly one of them updates it. The join @@ -36,6 +39,22 @@ type Querier interface { // An account qualifies only when every token, session, mail request, and // delivery row visible to the statement was locked above. DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) + // Lock order. Every transaction that writes mail_quota_usage first creates + // and locks all the usage rows it will touch with EnsureMailQuotaRows and + // LockMailQuotaRows, which both work in (period_kind, period_start) order, + // and only then writes them or a mail_quota_reservations row. Later UPDATE + // statements of the same transaction find their rows locked already, so the + // scan order of an UPDATE never decides the lock order. + // Creates the listed window rows of a provider account with no usage when + // they do not exist yet, in (period_kind, period_start) order. A window key + // is "/". A concurrent insert of the same row waits + // for the first transaction and then inserts nothing. Existing rows are + // neither changed nor locked here. + EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error + // Returns the newest open reservation of a delivery under a provider account + // made at or after reserved_since. A retry of the delivery inside the + // provider's idempotency window reuses it instead of counting again. + FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) // Among the versions of a family already effective at a time, the newest @@ -45,7 +64,13 @@ type Querier interface { GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + // Reads the status of the newest delivery of a kind addressed to an account, + // for the account's own view of its mail. It selects no address and no + // content. The recipient index narrows the scan to the account's rows. + GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error) GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error) + // Reads the usage of the day and the month window without locking. + GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error) // Reads the relay backlog for metrics without locking. Both subqueries use // the partial index on unpublished positions, so the cost follows the backlog // size, not the table size. The age comes from the database clock, the same @@ -66,6 +91,7 @@ type Querier interface { // for it. InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error + InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error // Stores a version and returns the stored row with the publication time and @@ -84,6 +110,15 @@ type Querier interface { InsertUser(ctx context.Context, arg InsertUserParams) error InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error) + // Lists the other accounts of a provider that have usage in a month, so + // startup can warn about a renamed EMAIL_ACCOUNT. + ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error) + // Locks the listed window rows until the transaction ends, in + // (period_kind, period_start) order, the same order for every caller, and + // returns their usage. Under READ COMMITTED a waiting caller reads the usage + // the first caller committed. period_starts narrows the index scan; + // window_keys selects the exact rows. + LockMailQuotaRows(ctx context.Context, arg LockMailQuotaRowsParams) ([]LockMailQuotaRowsRow, error) // Locks a request for the consumer transaction that turns it into a // delivery. A concurrent consumer of the same request waits here and then // finds the row deleted. The account cleanup and the cascade from users take @@ -99,6 +134,11 @@ type Querier interface { // because aggregate writers check the expected version, so scanning without a // position watermark cannot overtake an earlier version. LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) + // Records that the provider refused a send because the quota of a window is + // used up: the usage rises to at least the configured limit, so the local + // gate stops admitting sends until the window resets or an operator raises + // the limit. The caller holds the row lock. + MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error) // Marks the events that the broker acknowledged. The relay passes only IDs // whose rows its own transaction locked, so the statement never waits and the // count equals the number of distinct IDs. @@ -118,6 +158,16 @@ type Querier interface { // cannot both succeed. Content columns are not touched; a trigger refuses // any change to them. RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) + // Records the latest settled outcome of a send under the reservation. + RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error) + // Marks a reservation released. It matches only an open reservation, so a + // repeated release changes nothing and returns 0 rows. + ReleaseMailQuotaReservation(ctx context.Context, arg ReleaseMailQuotaReservationParams) (int64, error) + // Gives back recipients of a released reservation. The caller holds the row + // locks. A window that the provider reported exhausted keeps its usage: the + // provider's answer outranks the local count until the window resets. The + // count never drops below zero. + ReleaseMailQuotaUsage(ctx context.Context, arg ReleaseMailQuotaUsageParams) (int64, error) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) // Bounds a consumer transaction on the server, local to the transaction. diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 3a1a911..351682e 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -102,8 +102,8 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error { // start prepares the application without opening listeners. The mail // transport is selected before migrations, so a configuration that cannot -// start never changes the database. The demo policy seed runs after the -// migrations that create its table. +// start never changes the database. The demo policy seed and the mail quota +// report run after the migrations that create their tables. func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) { if err := config.Validate(); err != nil { return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err) @@ -118,6 +118,7 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App if err := seedDemoPolicy(ctx, config, logger); err != nil { return nil, nil, fmt.Errorf("bootstrap.start - seed demo policy: %w", err) } + reportMailQuota(ctx, config, logger) application, cleanup, err := initialize(ctx, config, logger, mailSender) if err != nil { return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err) diff --git a/backend/internal/bootstrap/mail_quota.go b/backend/internal/bootstrap/mail_quota.go new file mode 100644 index 0000000..aa3d262 --- /dev/null +++ b/backend/internal/bootstrap/mail_quota.go @@ -0,0 +1,53 @@ +package bootstrap + +import ( + "context" + "log/slog" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/notification" +) + +// startupQuotaReportTimeout bounds the two small reads of the startup quota +// report. +const startupQuotaReportTimeout = 10 * time.Second + +// reportMailQuota logs the configured provider account with its current day +// and month usage, and warns when the month has usage under another account +// label of the same provider, which is what a renamed EMAIL_ACCOUNT looks +// like. It runs after the startup migrations and under the same switch, is +// skipped for EMAIL_PROVIDER=disabled, and never stops startup: a failed +// read is logged as a warning. +func reportMailQuota(ctx context.Context, settings config.Config, logger *slog.Logger) { + if !settings.DatabaseMigrateOnStart || settings.DatabaseURL == "" || settings.EmailProvider == config.EmailProviderDisabled { + return + } + warn := func(message string, err error) { + logger.Warn(message, slog.String("error", err.Error())) + } + account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount) + if err != nil { + warn("mail quota usage was not reported: invalid provider account", err) + return + } + limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly)) + if err != nil { + warn("mail quota usage was not reported: invalid limits", err) + return + } + pool, err := postgres.NewPool(ctx, settings.DatabaseURL) + if err != nil { + warn("mail quota usage was not reported: create pool", err) + return + } + defer pool.Close() + ctx, cancel := context.WithTimeout(ctx, startupQuotaReportTimeout) + defer cancel() + reader := postgres.NewMailQuotaStore(pool).MailQuotas() + if err := notification.ReportQuotaUsage(ctx, reader, account, limits, time.Now(), logger); err != nil { + warn("mail quota usage was not reported", err) + } +} diff --git a/backend/internal/bootstrap/mail_test.go b/backend/internal/bootstrap/mail_test.go index dd24592..c81849c 100644 --- a/backend/internal/bootstrap/mail_test.go +++ b/backend/internal/bootstrap/mail_test.go @@ -154,6 +154,9 @@ func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) { settings := loadMailConfig(t, map[string]string{ "EMAIL_PROVIDER": "smtp", "DATABASE_URL": unreachableDatabaseURL, + // smtp has no quota default; see config.validateMailQuota. + "EMAIL_QUOTA_DAILY": "100", + "EMAIL_QUOTA_MONTHLY": "3000", }) logger, logs := captureLogs() @@ -186,6 +189,7 @@ func TestStartRejectsInvalidMailSettingsBeforeMigrations(t *testing.T) { {name: "timeout out of range", change: func(settings *config.Config) { settings.EmailTimeout = 0 }, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, {name: "Resend without key", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderResend }, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, {name: "SMTP without settings", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderSMTP }, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + {name: "quota turned off", change: func(settings *config.Config) { settings.EmailQuotaDaily = 0 }, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be an integer from 1 to 1000000000"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/backend/internal/domain/mail_quota.go b/backend/internal/domain/mail_quota.go new file mode 100644 index 0000000..7df6e1e --- /dev/null +++ b/backend/internal/domain/mail_quota.go @@ -0,0 +1,112 @@ +package domain + +import ( + "errors" + "fmt" + "time" +) + +// ErrInvalidMailQuota reports quota limits or a quota window that break a +// quota rule. +var ErrInvalidMailQuota = errors.New("invalid mail quota") + +// MailQuotaPeriod is a quota window kind. Both windows are UTC calendar +// periods, as the Resend Free plan counts them: a day starts at 00:00 UTC and +// a month on its first day at 00:00 UTC. +type MailQuotaPeriod string + +const ( + MailQuotaPeriodDay MailQuotaPeriod = "day" + MailQuotaPeriodMonth MailQuotaPeriod = "month" +) + +// MailQuotaLimits are the recipients that one provider account may be sent +// per UTC day and per UTC calendar month. Every recipient counts, as +// providers count them. The values come from configuration, never from +// domain constants, because they follow the provider plan of the stand. +type MailQuotaLimits struct { + daily int64 + monthly int64 +} + +// NewMailQuotaLimits accepts positive limits where the daily limit does not +// exceed the monthly one. A zero limit is refused rather than read as +// "unlimited": no setting turns the quota off. +func NewMailQuotaLimits(daily, monthly int64) (MailQuotaLimits, error) { + switch { + case daily <= 0 || monthly <= 0: + return MailQuotaLimits{}, fmt.Errorf("domain.NewMailQuotaLimits - limits must be positive: %w", ErrInvalidMailQuota) + case daily > monthly: + return MailQuotaLimits{}, fmt.Errorf("domain.NewMailQuotaLimits - the daily limit must not exceed the monthly limit: %w", ErrInvalidMailQuota) + } + return MailQuotaLimits{daily: daily, monthly: monthly}, nil +} + +func (limits MailQuotaLimits) IsZero() bool { return limits.daily == 0 } + +func (limits MailQuotaLimits) Daily() int64 { return limits.daily } + +func (limits MailQuotaLimits) Monthly() int64 { return limits.monthly } + +// Of returns the limit of a period; zero for an unknown period. +func (limits MailQuotaLimits) Of(period MailQuotaPeriod) int64 { + switch period { + case MailQuotaPeriodDay: + return limits.daily + case MailQuotaPeriodMonth: + return limits.monthly + default: + return 0 + } +} + +// MailQuotaWindows are the UTC day and the UTC calendar month that contain +// one instant. A reservation counts against both. +type MailQuotaWindows struct { + dayStart time.Time + monthStart time.Time +} + +// MailQuotaWindowsAt returns the windows that contain at, in UTC whatever +// the location of at. +func MailQuotaWindowsAt(at time.Time) MailQuotaWindows { + utc := at.UTC() + return MailQuotaWindows{ + dayStart: time.Date(utc.Year(), utc.Month(), utc.Day(), 0, 0, 0, 0, time.UTC), + monthStart: time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC), + } +} + +func (windows MailQuotaWindows) IsZero() bool { return windows.dayStart.IsZero() } + +// DayStart is 00:00 UTC of the day. +func (windows MailQuotaWindows) DayStart() time.Time { return windows.dayStart } + +// MonthStart is 00:00 UTC of the first day of the month. +func (windows MailQuotaWindows) MonthStart() time.Time { return windows.monthStart } + +// Start returns the start of a period; the zero time for an unknown period. +func (windows MailQuotaWindows) Start(period MailQuotaPeriod) time.Time { + switch period { + case MailQuotaPeriodDay: + return windows.dayStart + case MailQuotaPeriodMonth: + return windows.monthStart + default: + return time.Time{} + } +} + +// ResetAt returns when a period ends and its count starts again from zero: +// the next 00:00 UTC for the day, the first day of the next month at 00:00 +// UTC for the month. The zero time for an unknown period. +func (windows MailQuotaWindows) ResetAt(period MailQuotaPeriod) time.Time { + switch period { + case MailQuotaPeriodDay: + return windows.dayStart.AddDate(0, 0, 1) + case MailQuotaPeriodMonth: + return windows.monthStart.AddDate(0, 1, 0) + default: + return time.Time{} + } +} diff --git a/backend/internal/domain/mail_quota_test.go b/backend/internal/domain/mail_quota_test.go new file mode 100644 index 0000000..b7b7346 --- /dev/null +++ b/backend/internal/domain/mail_quota_test.go @@ -0,0 +1,120 @@ +package domain + +import ( + "errors" + "testing" + "time" +) + +func TestMailQuotaWindowsAtUsesUTCCalendarPeriods(t *testing.T) { + moscow := time.FixedZone("UTC+3", 3*60*60) + tests := []struct { + name string + at time.Time + dayStart, monthStart time.Time + dayReset, monthReset time.Time + }{ + { + name: "middle of a day", + at: time.Date(2026, 10, 6, 12, 30, 0, 0, time.UTC), + dayStart: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "exactly at midnight UTC belongs to the new day", + at: time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC), + dayStart: time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2026, 10, 8, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "one nanosecond before midnight UTC belongs to the old day", + at: time.Date(2026, 10, 6, 23, 59, 59, 999999999, time.UTC), + dayStart: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "local time after local midnight is still the previous UTC day", + at: time.Date(2026, 11, 1, 1, 0, 0, 0, moscow), + dayStart: time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "leap day", + at: time.Date(2028, 2, 29, 18, 0, 0, 0, time.UTC), + dayStart: time.Date(2028, 2, 29, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2028, 2, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2028, 3, 1, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2028, 3, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "February of a common year", + at: time.Date(2027, 2, 28, 18, 0, 0, 0, time.UTC), + dayStart: time.Date(2027, 2, 28, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2027, 3, 1, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2027, 3, 1, 0, 0, 0, 0, time.UTC), + }, + { + name: "December resets into January of the next year", + at: time.Date(2026, 12, 31, 23, 0, 0, 0, time.UTC), + dayStart: time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC), + monthStart: time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC), + dayReset: time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), + monthReset: time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + windows := MailQuotaWindowsAt(test.at) + if !windows.DayStart().Equal(test.dayStart) || windows.DayStart().Location() != time.UTC { + t.Fatalf("DayStart() = %s, want %s in UTC", windows.DayStart(), test.dayStart) + } + if !windows.MonthStart().Equal(test.monthStart) || windows.Start(MailQuotaPeriodMonth) != windows.MonthStart() { + t.Fatalf("MonthStart() = %s, want %s", windows.MonthStart(), test.monthStart) + } + if got := windows.ResetAt(MailQuotaPeriodDay); !got.Equal(test.dayReset) { + t.Fatalf("ResetAt(day) = %s, want %s", got, test.dayReset) + } + if got := windows.ResetAt(MailQuotaPeriodMonth); !got.Equal(test.monthReset) { + t.Fatalf("ResetAt(month) = %s, want %s", got, test.monthReset) + } + // The reset instant opens the next window. + if next := MailQuotaWindowsAt(test.dayReset); !next.DayStart().Equal(test.dayReset) { + t.Fatalf("the day reset %s does not start the next day window", test.dayReset) + } + }) + } +} + +func TestNewMailQuotaLimits(t *testing.T) { + limits, err := NewMailQuotaLimits(100, 3000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + if limits.Of(MailQuotaPeriodDay) != 100 || limits.Of(MailQuotaPeriodMonth) != 3000 || limits.Of("week") != 0 { + t.Fatalf("limits = %d/%d", limits.Daily(), limits.Monthly()) + } + if _, err := NewMailQuotaLimits(3000, 3000); err != nil { + t.Fatalf("equal limits: error = %v", err) + } + for name, values := range map[string][2]int64{ + "zero daily": {0, 3000}, + "zero monthly": {100, 0}, + "negative": {-1, 3000}, + "daily above monthly": {3001, 3000}, + } { + t.Run(name, func(t *testing.T) { + if _, err := NewMailQuotaLimits(values[0], values[1]); !errors.Is(err, ErrInvalidMailQuota) { + t.Fatalf("NewMailQuotaLimits(%d, %d) error = %v, want ErrInvalidMailQuota", values[0], values[1], err) + } + }) + } +} diff --git a/backend/internal/port/outbound/delivery.go b/backend/internal/port/outbound/delivery.go index 2ab7118..be48dfc 100644 --- a/backend/internal/port/outbound/delivery.go +++ b/backend/internal/port/outbound/delivery.go @@ -3,6 +3,7 @@ package outbound import ( "context" "errors" + "time" "github.com/google/uuid" @@ -66,6 +67,11 @@ type DeliveryRepository interface { // next.Version() - 1. Otherwise it returns ErrDeliveryVersionConflict. WaitForQuota(ctx context.Context, next domain.Delivery) error + // LatestForRecipient returns the status of the newest delivery of kind + // addressed to the account, by creation time, or ErrDeliveryNotFound + // when there is none. It reads no address and no content. + LatestForRecipient(ctx context.Context, recipientUserID uuid.UUID, kind domain.MailKind) (DeliveryStatusSnapshot, error) + // Rebind stores the provider account of next as returned by // domain.Delivery.Rebind under the same version rule as WaitForQuota. A // delivery that has an attempt meanwhile fails with @@ -74,6 +80,17 @@ type DeliveryRepository interface { Rebind(ctx context.Context, next domain.Delivery) error } +// DeliveryStatusSnapshot is the state of a delivery without its recipient +// address or content. A zero NextAttemptAt means none is scheduled. +type DeliveryStatusSnapshot struct { + DeliveryID uuid.UUID + Kind domain.MailKind + Status domain.DeliveryStatus + NextAttemptAt time.Time + CreatedAt time.Time + UpdatedAt time.Time +} + // MailRequestRepository stores mail requests between the producer // transaction and the consumer transaction that turns them into deliveries. // Errors never quote the request text. diff --git a/backend/internal/port/outbound/mail.go b/backend/internal/port/outbound/mail.go index 3b1bcf8..90c4de7 100644 --- a/backend/internal/port/outbound/mail.go +++ b/backend/internal/port/outbound/mail.go @@ -196,6 +196,14 @@ type SendResult struct { // wait the transport derived from documented provider rules (for example // the next daily quota reset). It is zero when there is neither. RetryAfter time.Duration + + // QuotaPeriod names the provider quota window that is used up, for + // MailRejectionQuotaExhausted only: domain.MailQuotaPeriodDay or + // domain.MailQuotaPeriodMonth when the provider said which, for example + // Resend's daily_quota_exceeded and monthly_quota_exceeded; empty when it + // did not. The quota gate marks that window instead of guessing it from + // RetryAfter. + QuotaPeriod domain.MailQuotaPeriod } // MailSender hands one message to the configured transport. diff --git a/backend/internal/port/outbound/mail_quota.go b/backend/internal/port/outbound/mail_quota.go new file mode 100644 index 0000000..077b403 --- /dev/null +++ b/backend/internal/port/outbound/mail_quota.go @@ -0,0 +1,135 @@ +package outbound + +import ( + "context" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// MailQuotaReservation is a number of recipients counted against the day and +// the month window of one provider account for one send of one delivery. ID +// names its journal row. +type MailQuotaReservation struct { + ID uuid.UUID + DeliveryID uuid.UUID + Account domain.MailProviderAccount + Windows domain.MailQuotaWindows + Recipients int64 + ReservedAt time.Time +} + +// MailQuotaReserveRequest asks to count Reservation, which carries a new ID +// and the reservation time. +type MailQuotaReserveRequest struct { + Reservation MailQuotaReservation + Limits domain.MailQuotaLimits + // ReuseSince enables reuse: an open reservation of the same delivery and + // account made at or after it is returned instead of counting again. The + // zero time disables reuse. + ReuseSince time.Time +} + +// MailQuotaCheck reports which window limits a reservation would exceed. A +// reservation took place only when neither is exceeded. +type MailQuotaCheck struct { + DayExceeded bool + MonthExceeded bool +} + +// Reserved reports that the recipients are counted against both windows. +func (check MailQuotaCheck) Reserved() bool { return !check.DayExceeded && !check.MonthExceeded } + +// MailQuotaReserveResult is the outcome of Reserve. Reservation is the new +// or reused reservation when Check.Reserved(); it is zero otherwise. +type MailQuotaReserveResult struct { + Check MailQuotaCheck + Reservation MailQuotaReservation + // Reused reports an open reservation of an earlier attempt of the same + // delivery: nothing was counted again. + Reused bool +} + +// MailQuotaOutcome is what a send under a reservation established, as the +// journal records it. +type MailQuotaOutcome string + +const ( + MailQuotaOutcomeAccepted MailQuotaOutcome = "accepted" + MailQuotaOutcomeUnknown MailQuotaOutcome = "unknown" + MailQuotaOutcomeRejected MailQuotaOutcome = "rejected" + // MailQuotaOutcomeNotSent means that Send returned an error: nothing left + // the process. + MailQuotaOutcomeNotSent MailQuotaOutcome = "not_sent" +) + +// MailQuotaSettlement applies the result of a send to the counters. +type MailQuotaSettlement struct { + Reservation MailQuotaReservation + Outcome MailQuotaOutcome + // Release gives the reservation back, once: a repeated release of the + // same reservation changes nothing. + Release bool + // ExhaustedPeriod, when set, marks that window of ExhaustedWindows full + // up to ExhaustedLimit, because the provider refused for its quota. + ExhaustedPeriod domain.MailQuotaPeriod + ExhaustedWindows domain.MailQuotaWindows + ExhaustedLimit int64 + At time.Time +} + +// MailQuotaUsage is the usage of one account in a day and a month window. A +// zero time means that the provider has not refused in that window. +type MailQuotaUsage struct { + DayUsed int64 + MonthUsed int64 + DayProviderExhaustedAt time.Time + MonthProviderExhaustedAt time.Time +} + +// MailQuotaUsageReader reads quota usage without locking, for startup +// reports, operators, and metrics. +type MailQuotaUsageReader interface { + // Usage returns zero usage for windows without a row. + Usage(ctx context.Context, account domain.MailProviderAccount, windows domain.MailQuotaWindows) (MailQuotaUsage, error) + + // OtherAccountsWithUsage lists the other account labels of the same + // provider that have usage in the month starting at monthStart. + OtherAccountsWithUsage(ctx context.Context, account domain.MailProviderAccount, monthStart time.Time) ([]string, error) +} + +// MailQuotaRepository counts the recipients sent through each provider +// account per UTC day and UTC month, with a journal of reservations. The +// writes are available only through UnitOfWork, because they lock rows until +// the transaction ends; callers commit before they call a transport, so a +// slow provider never holds the locks. +// +// Every write locks all the window rows it touches in one statement, in +// (period_kind, period_start) order, before it writes them or the journal, +// so two quota writers wait for each other on these rows in one direction +// only, whatever plan PostgreSQL chooses. Callers that lock other rows in +// the same transaction keep their own consistent order for those. +// +// The counters and the journal do not cascade from accounts or deliveries: +// the provider keeps counting messages whose recipient account was deleted. +type MailQuotaRepository interface { + MailQuotaUsageReader + + // Reserve first looks for a reusable open reservation (see + // MailQuotaReserveRequest.ReuseSince) and returns it with Reused set, + // counting nothing. Otherwise it adds the recipients to the day and the + // month window when both stay within limits, and to neither otherwise, + // and journals the reservation. Concurrent reservations for the same + // account never exceed a limit together. A limit lowered below the + // current usage refuses every new reservation until the window resets. + Reserve(ctx context.Context, request MailQuotaReserveRequest) (MailQuotaReserveResult, error) + + // Settle records the outcome in the journal, gives the recipients back + // when Release is set and the reservation is still open, and marks the + // exhausted window. It reports whether this call released the + // reservation. A window that the provider reported exhausted keeps its + // usage on release. + Settle(ctx context.Context, settlement MailQuotaSettlement) (released bool, err error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index aaabced..cee8f8e 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -52,6 +52,7 @@ type UnitOfWork interface { Policies() PolicyRepository Deliveries() DeliveryRepository MailRequests() MailRequestRepository + MailQuotas() MailQuotaRepository Outbox() OutboxWriter } diff --git a/backend/internal/usecase/notification/delivery_status.go b/backend/internal/usecase/notification/delivery_status.go new file mode 100644 index 0000000..7c1db61 --- /dev/null +++ b/backend/internal/usecase/notification/delivery_status.go @@ -0,0 +1,79 @@ +package notification + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// UserDeliveryStatus is what an account may see about its own latest mail +// of a kind: the status and, while it waits for a quota reset, until when. +// It carries no address, subject, body, provider, or delivery ID. +// +// A user interface maps it as follows: +// +// - waiting_quota with WaitingUntil: "your email is waiting until +// "; without WaitingUntil: "your email is waiting; the +// time is not known yet"; +// - pending and unknown: "your email is being sent". unknown is not shown +// as a failure: the message may have been accepted; +// - accepted: "your email was sent". It means that the provider accepted +// it, not that it reached the inbox; +// - rejected: "your email could not be sent". +type UserDeliveryStatus struct { + Kind domain.MailKind + Status domain.DeliveryStatus + // WaitingUntil is the expected quota reset for waiting_quota; zero for + // other statuses or when the reset is unknown. + WaitingUntil time.Time + // UpdatedAt is when the status last changed. + UpdatedAt time.Time +} + +// WaitingForQuota reports a message that waits for a quota reset. +func (status UserDeliveryStatus) WaitingForQuota() bool { + return status.Status == domain.DeliveryStatusWaitingQuota +} + +// DeliveryStatusReader shows an account the status of its own mail. It reads +// outside a transaction; the identity flows and a later API expose it. +type DeliveryStatusReader struct { + deliveries outbound.DeliveryRepository +} + +func NewDeliveryStatusReader(deliveries outbound.DeliveryRepository) *DeliveryStatusReader { + return &DeliveryStatusReader{deliveries: deliveries} +} + +// LatestForUser returns the status of the newest delivery of kind addressed +// to userID, and false when there is none. userID must be the authenticated +// account itself: the query is scoped to deliveries addressed to it, so it +// cannot read another account's mail, and callers must never take the ID +// from request input. +func (reader *DeliveryStatusReader) LatestForUser(ctx context.Context, userID uuid.UUID, kind domain.MailKind) (UserDeliveryStatus, bool, error) { + const location = "DeliveryStatusReader.LatestForUser" + if userID == uuid.Nil { + return UserDeliveryStatus{}, false, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidDelivery) + } + if _, err := domain.ParseMailKind(string(kind)); err != nil { + return UserDeliveryStatus{}, false, fmt.Errorf("%s - %w", location, err) + } + snapshot, err := reader.deliveries.LatestForRecipient(ctx, userID, kind) + if errors.Is(err, outbound.ErrDeliveryNotFound) { + return UserDeliveryStatus{}, false, nil + } + if err != nil { + return UserDeliveryStatus{}, false, fmt.Errorf("%s - read latest delivery: %w", location, err) + } + status := UserDeliveryStatus{Kind: snapshot.Kind, Status: snapshot.Status, UpdatedAt: snapshot.UpdatedAt} + if snapshot.Status == domain.DeliveryStatusWaitingQuota { + status.WaitingUntil = snapshot.NextAttemptAt + } + return status, true, nil +} diff --git a/backend/internal/usecase/notification/delivery_status_test.go b/backend/internal/usecase/notification/delivery_status_test.go new file mode 100644 index 0000000..5aeaaa5 --- /dev/null +++ b/backend/internal/usecase/notification/delivery_status_test.go @@ -0,0 +1,84 @@ +package notification + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type statusDeliveries struct { + outbound.DeliveryRepository + + snapshot outbound.DeliveryStatusSnapshot + err error + asked []uuid.UUID +} + +func (deliveries *statusDeliveries) LatestForRecipient(_ context.Context, recipientUserID uuid.UUID, _ domain.MailKind) (outbound.DeliveryStatusSnapshot, error) { + deliveries.asked = append(deliveries.asked, recipientUserID) + return deliveries.snapshot, deliveries.err +} + +func TestDeliveryStatusReaderShowsOnlyTheUserSafeStatus(t *testing.T) { + userID := uuid.Must(uuid.NewV7()) + resetAt := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + changed := time.Date(2026, 10, 6, 22, 0, 0, 0, time.UTC) + tests := []struct { + name string + status domain.DeliveryStatus + next time.Time + wantWaiting bool + wantUntil time.Time + }{ + {name: "waiting for a known reset", status: domain.DeliveryStatusWaitingQuota, next: resetAt, wantWaiting: true, wantUntil: resetAt}, + {name: "waiting for an unknown reset", status: domain.DeliveryStatusWaitingQuota, wantWaiting: true}, + {name: "pending shows no wait time", status: domain.DeliveryStatusPending, next: resetAt}, + {name: "unknown", status: domain.DeliveryStatusUnknown}, + {name: "accepted", status: domain.DeliveryStatusAccepted}, + {name: "rejected", status: domain.DeliveryStatusRejected}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + deliveries := &statusDeliveries{snapshot: outbound.DeliveryStatusSnapshot{ + DeliveryID: uuid.Must(uuid.NewV7()), Kind: domain.MailKindVerification, Status: test.status, + NextAttemptAt: test.next, CreatedAt: changed, UpdatedAt: changed, + }} + status, found, err := NewDeliveryStatusReader(deliveries).LatestForUser(t.Context(), userID, domain.MailKindVerification) + if err != nil || !found { + t.Fatalf("LatestForUser() = %t, %v; want a status", found, err) + } + if status.Status != test.status || status.Kind != domain.MailKindVerification || !status.UpdatedAt.Equal(changed) { + t.Fatalf("status = %+v", status) + } + if status.WaitingForQuota() != test.wantWaiting || !status.WaitingUntil.Equal(test.wantUntil) { + t.Fatalf("waiting %t until %s, want %t until %s", status.WaitingForQuota(), status.WaitingUntil, test.wantWaiting, test.wantUntil) + } + if len(deliveries.asked) != 1 || deliveries.asked[0] != userID { + t.Fatal("the reader did not scope the query to the user") + } + }) + } +} + +func TestDeliveryStatusReaderWithoutADelivery(t *testing.T) { + reader := NewDeliveryStatusReader(&statusDeliveries{err: outbound.ErrDeliveryNotFound}) + if _, found, err := reader.LatestForUser(t.Context(), uuid.Must(uuid.NewV7()), domain.MailKindNotification); err != nil || found { + t.Fatalf("LatestForUser() = %t, %v; want nothing found", found, err) + } + failing := NewDeliveryStatusReader(&statusDeliveries{err: errStorageDown}) + if _, _, err := failing.LatestForUser(t.Context(), uuid.Must(uuid.NewV7()), domain.MailKindNotification); !errors.Is(err, errStorageDown) { + t.Fatalf("LatestForUser() error = %v, want the storage error", err) + } + if _, _, err := reader.LatestForUser(t.Context(), uuid.Nil, domain.MailKindNotification); !errors.Is(err, domain.ErrInvalidDelivery) { + t.Fatalf("LatestForUser(nil user) error = %v, want ErrInvalidDelivery", err) + } + if _, _, err := reader.LatestForUser(t.Context(), uuid.Must(uuid.NewV7()), "invitation"); !errors.Is(err, domain.ErrInvalidMailContent) { + t.Fatalf("LatestForUser(unknown kind) error = %v, want ErrInvalidMailContent", err) + } +} diff --git a/backend/internal/usecase/notification/quota.go b/backend/internal/usecase/notification/quota.go new file mode 100644 index 0000000..eedefb5 --- /dev/null +++ b/backend/internal/usecase/notification/quota.go @@ -0,0 +1,340 @@ +package notification + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// recipientsPerDelivery is what one send of a delivery counts against the +// quota: a delivery addresses exactly one recipient, and providers count +// every recipient of a message. +const recipientsPerDelivery = 1 + +var ( + // ErrQuotaNotConfigured reports a delivery pinned to a provider account + // other than the configured one. No limits are known for it, so it must + // not be sent: an account without a quota never means "unlimited". + ErrQuotaNotConfigured = errors.New("no mail quota is configured for the delivery's provider account") + + // ErrInvalidQuotaPermit reports a settlement without the permit that + // PrepareSend returned, or with a send result that is not an outcome. + ErrInvalidQuotaPermit = errors.New("invalid quota permit or send result") +) + +// QuotaGate admits sends within the quota of the configured provider +// account: recipients per UTC day and per UTC calendar month, from +// EMAIL_QUOTA_DAILY and EMAIL_QUOTA_MONTHLY. It is provider-agnostic and +// runs before any transport is called, so every transport, SMTP included, is +// subject to it; there is no path around it. +// +// The gate only defers. It never buys a plan, switches to a paid tier, or +// moves a delivery to another transport, provider, or account when a quota +// is used up: the delivery waits for the reset in waiting_quota, and an +// operator may decide otherwise. +// +// The sending worker (TASK-016) uses it in two transactions around one +// transport call: +// +// 1. PrepareSend in the transaction that claims a due delivery. It either +// returns a permit, or parks the delivery in waiting_quota until the +// reset. Commit before calling the transport, so a slow provider never +// holds the quota row locks. +// 2. SettleSend in the transaction that stores the attempt result (or, when +// Send returned an error, the delivery's next state). The reservation +// journal makes a repeated settlement harmless. +type QuotaGate struct { + account domain.MailProviderAccount + limits domain.MailQuotaLimits + idempotencyWindow time.Duration + clock func() time.Time + logger *slog.Logger +} + +// NewQuotaGate builds the gate for the configured provider account and its +// limits. idempotencyWindow is how long the provider deduplicates a repeated +// request with the same idempotency key, for example +// resend.IdempotencyWindow; zero for a transport without provider-side +// deduplication, such as SMTP, where every retry counts again. clock is the +// application clock; tests pass a fake one. +func NewQuotaGate( + account domain.MailProviderAccount, + limits domain.MailQuotaLimits, + idempotencyWindow time.Duration, + clock func() time.Time, + logger *slog.Logger, +) *QuotaGate { + return &QuotaGate{account: account, limits: limits, idempotencyWindow: idempotencyWindow, clock: clock, logger: logger} +} + +// QuotaPermit admits one send of one delivery. It holds the reservation, so +// a settlement after midnight still releases the windows the send was +// counted in. +type QuotaPermit struct { + reservation outbound.MailQuotaReservation + reused bool +} + +func (permit QuotaPermit) IsZero() bool { return permit.reservation.ID == uuid.Nil } + +// Reused reports a permit that continues the open reservation of an earlier +// attempt of the same delivery inside the provider's idempotency window. +func (permit QuotaPermit) Reused() bool { return permit.reused } + +// SendDecision is the result of PrepareSend. +type SendDecision struct { + // Delivery is the delivery after the decision: unchanged when the send + // may proceed or when an unknown delivery must wait, otherwise the stored + // waiting_quota state with NextAttemptAt at ResetAt. + Delivery domain.Delivery + // Permit admits the send; zero when the send must wait. + Permit QuotaPermit + // ResetAt is when the delivery may try again: the reset of the exhausted + // window, the next 00:00 UTC for the day or the first day of the next + // month for the month. Zero when the send may proceed. + ResetAt time.Time +} + +// Proceed reports that the caller may call the transport now. +func (decision SendDecision) Proceed() bool { return !decision.Permit.IsZero() } + +// PrepareSend reserves the delivery's recipients against the day and the +// month window of its provider account, in unit's transaction. +// +// A retry inside the idempotency window of an earlier attempt that is still +// counted (the outcome was unknown, or its process stopped before settling) +// reuses that reservation and proceeds without counting again: the provider +// answers a repeated key with the original result and does not send twice. +// +// Otherwise, when both windows have room, it returns a new permit and leaves +// the delivery unchanged. When a window is full, nothing is reserved, and +// the delivery waits until the later reset of the full windows: +// +// - a pending or waiting_quota delivery is stored as waiting_quota with +// NextAttemptAt at the reset, which is what an operator and the user's +// status view (DeliveryStatusReader) read; +// - an unknown delivery is returned unchanged with ResetAt: its retry +// belongs to the retry policy (TASK-017), and parking it would hide that +// an earlier attempt may have been accepted. +// +// The caller chooses which deliveries are due. A delivery pinned to another +// provider account returns ErrQuotaNotConfigured; an accepted or rejected +// one returns domain.ErrDeliveryTransition. +func (gate *QuotaGate) PrepareSend(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery) (SendDecision, error) { + const location = "QuotaGate.PrepareSend" + if delivery.IsZero() { + return SendDecision{}, fmt.Errorf("%s - delivery was not built by domain.NewDelivery or RestoreDelivery: %w", location, domain.ErrInvalidDelivery) + } + if delivery.ProviderAccount() != gate.account { + return SendDecision{}, fmt.Errorf("%s - delivery %s: %w", location, delivery.ID(), ErrQuotaNotConfigured) + } + if delivery.Status().IsTerminal() { + return SendDecision{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.Status(), domain.ErrDeliveryTransition) + } + now := gate.clock() + reservationID, err := uuid.NewV7() + if err != nil { + return SendDecision{}, fmt.Errorf("%s - generate reservation ID: %w", location, err) + } + request := outbound.MailQuotaReserveRequest{ + Reservation: outbound.MailQuotaReservation{ + ID: reservationID, + DeliveryID: delivery.ID(), + Account: gate.account, + Windows: domain.MailQuotaWindowsAt(now), + Recipients: recipientsPerDelivery, + ReservedAt: now, + }, + Limits: gate.limits, + } + if gate.idempotencyWindow > 0 { + request.ReuseSince = now.Add(-gate.idempotencyWindow) + } + result, err := unit.MailQuotas().Reserve(ctx, request) + if err != nil { + return SendDecision{}, fmt.Errorf("%s - reserve quota: %w", location, err) + } + if result.Check.Reserved() { + return SendDecision{Delivery: delivery, Permit: QuotaPermit{reservation: result.Reservation, reused: result.Reused}}, nil + } + + // A full month outlasts a full day, so the month reset wins. + period := domain.MailQuotaPeriodDay + if result.Check.MonthExceeded { + period = domain.MailQuotaPeriodMonth + } + resetAt := request.Reservation.Windows.ResetAt(period) + if delivery.Status() == domain.DeliveryStatusUnknown { + return SendDecision{Delivery: delivery, ResetAt: resetAt}, nil + } + // Another instance whose clock runs a little ahead may have changed the + // delivery last; the change time must not precede it, and the reset must + // not precede the change. + at := latest(now, delivery.UpdatedAt()) + resetAt = latest(resetAt, at) + parked, err := delivery.WaitForQuota(at, resetAt) + if err != nil { + return SendDecision{}, fmt.Errorf("%s - park delivery: %w", location, err) + } + if err := unit.Deliveries().WaitForQuota(ctx, parked); err != nil { + return SendDecision{}, fmt.Errorf("%s - store waiting delivery: %w", location, err) + } + gate.logger.InfoContext(ctx, "mail quota is used up; the delivery waits for the reset", + slog.String("delivery_id", delivery.ID().String()), + slog.String("provider", gate.account.Provider()), + slog.String("period", string(period)), + slog.Time("reset_at", resetAt)) + return SendDecision{Delivery: parked, ResetAt: resetAt}, nil +} + +// SettleSend applies the result of the send that permit admitted to the +// quota, in unit's transaction, and journals the outcome: +// +// - sendErr is not nil, or the outcome is rejected: the message did not +// leave the process, or the provider refused it, so the provider did not +// count it and a new reservation is released. A reused reservation is +// kept: the earlier attempt under it may have been sent. +// - accepted or unknown: the reservation stays. An unknown attempt may +// have been sent, so it counts. +// - rejected with quota_exhausted: the provider's answer refines the local +// count, see providerExhausted, and the returned time is when the +// delivery waits for; the caller stores it as the attempt's +// NextAttemptAt. Zero means that the reset is unknown. +// +// The returned time is zero for every other result. A repeated settlement +// of the same permit releases nothing a second time. +func (gate *QuotaGate) SettleSend( + ctx context.Context, + unit outbound.UnitOfWork, + permit QuotaPermit, + result outbound.SendResult, + sendErr error, +) (time.Time, error) { + const location = "QuotaGate.SettleSend" + if permit.IsZero() { + return time.Time{}, fmt.Errorf("%s - permit is required: %w", location, ErrInvalidQuotaPermit) + } + now := gate.clock() + settlement := outbound.MailQuotaSettlement{Reservation: permit.reservation, At: latest(now, permit.reservation.ReservedAt)} + // A Send error means that the message never left the process; the + // result is zero then and is not read (see outbound.MailSender). + switch { + case sendErr != nil: + settlement.Outcome = outbound.MailQuotaOutcomeNotSent + case result.Outcome == outbound.MailOutcomeAccepted: + settlement.Outcome = outbound.MailQuotaOutcomeAccepted + case result.Outcome == outbound.MailOutcomeUnknown: + settlement.Outcome = outbound.MailQuotaOutcomeUnknown + case result.Outcome == outbound.MailOutcomeRejected: + settlement.Outcome = outbound.MailQuotaOutcomeRejected + default: + return time.Time{}, fmt.Errorf("%s - send result has no outcome: %w", location, ErrInvalidQuotaPermit) + } + notTaken := settlement.Outcome == outbound.MailQuotaOutcomeNotSent || settlement.Outcome == outbound.MailQuotaOutcomeRejected + settlement.Release = notTaken && !permit.reused + + var until time.Time + if sendErr == nil && result.Rejection == outbound.MailRejectionQuotaExhausted { + until = gate.providerExhausted(&settlement, result, now) + } + if _, err := unit.MailQuotas().Settle(ctx, settlement); err != nil { + return time.Time{}, fmt.Errorf("%s - settle reservation: %w", location, err) + } + if settlement.ExhaustedPeriod != "" { + gate.logger.WarnContext(ctx, "the mail provider reported its quota used up; local sending stops until the reset", + slog.String("provider", gate.account.Provider()), + slog.String("period", string(settlement.ExhaustedPeriod)), + slog.Time("reset_at", until)) + } + return until, nil +} + +// providerExhausted handles a provider answer that its quota is used up: it +// adds the window to mark to settlement and returns when the delivery waits +// for. +// +// The window comes from the provider's own answer (SendResult.QuotaPeriod), +// never from the wait hint, and is taken at settlement time: the provider +// answered about the window that is current when the answer arrives, even +// when the reservation was made before midnight. The day mark raises the +// day's usage to the daily limit and the delivery waits for the next 00:00 +// UTC; the month mark raises the month's usage to the monthly limit and the +// delivery waits for the next UTC month start. Resend's monthly quota +// follows the account's billing cycle; when that cycle resets later than +// the calendar month, the retry at the month start is refused again and +// waits another month unless an operator decides otherwise. +// +// Without a named window nothing is marked: the delivery waits for the +// provider's hint, or without one for an operator (zero time). +// +// Marking stops the gate from admitting sends that the provider would +// refuse; raising the limit is the operator's way to reopen the window. +func (gate *QuotaGate) providerExhausted(settlement *outbound.MailQuotaSettlement, result outbound.SendResult, now time.Time) time.Time { + switch result.QuotaPeriod { + case domain.MailQuotaPeriodDay, domain.MailQuotaPeriodMonth: + windows := domain.MailQuotaWindowsAt(now) + settlement.ExhaustedPeriod = result.QuotaPeriod + settlement.ExhaustedWindows = windows + settlement.ExhaustedLimit = gate.limits.Of(result.QuotaPeriod) + return windows.ResetAt(result.QuotaPeriod) + default: + if result.RetryAfter > 0 { + return now.Add(result.RetryAfter) + } + return time.Time{} + } +} + +// ReportQuotaUsage logs the usage of the configured account in the current +// day and month, and warns when other accounts of the same provider have +// usage this month: a renamed EMAIL_ACCOUNT starts a new local count while +// the provider keeps the old one. It never fails startup; the caller logs +// the error. +func ReportQuotaUsage( + ctx context.Context, + reader outbound.MailQuotaUsageReader, + account domain.MailProviderAccount, + limits domain.MailQuotaLimits, + now time.Time, + logger *slog.Logger, +) error { + const location = "notification.ReportQuotaUsage" + windows := domain.MailQuotaWindowsAt(now) + usage, err := reader.Usage(ctx, account, windows) + if err != nil { + return fmt.Errorf("%s - read usage: %w", location, err) + } + logger.InfoContext(ctx, "mail quota usage", + slog.String("provider", account.Provider()), + slog.String("account", account.Account()), + slog.Int64("day_used", usage.DayUsed), + slog.Int64("day_limit", limits.Daily()), + slog.Int64("month_used", usage.MonthUsed), + slog.Int64("month_limit", limits.Monthly())) + others, err := reader.OtherAccountsWithUsage(ctx, account, windows.MonthStart()) + if err != nil { + return fmt.Errorf("%s - read other accounts: %w", location, err) + } + if len(others) > 0 { + // Account labels are configuration identity, never credentials. + logger.WarnContext(ctx, "other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count", + slog.String("provider", account.Provider()), + slog.String("account", account.Account()), + slog.Any("other_accounts", others)) + } + return nil +} + +func latest(first, second time.Time) time.Time { + if second.After(first) { + return second + } + return first +} diff --git a/backend/internal/usecase/notification/quota_test.go b/backend/internal/usecase/notification/quota_test.go new file mode 100644 index 0000000..4829b00 --- /dev/null +++ b/backend/internal/usecase/notification/quota_test.go @@ -0,0 +1,572 @@ +package notification + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type quotaWindowKey struct { + period domain.MailQuotaPeriod + start time.Time +} + +type quotaWindowState struct { + used int64 + providerExhausted bool +} + +type journalEntry struct { + reservation outbound.MailQuotaReservation + released bool + outcome outbound.MailQuotaOutcome +} + +// memoryQuotas counts in memory with the rules of the PostgreSQL store, +// journal included. Concurrency is covered by the integration tests. +type memoryQuotas struct { + windows map[quotaWindowKey]*quotaWindowState + journal []*journalEntry + accounts map[domain.MailProviderAccount]bool +} + +func newMemoryQuotas() *memoryQuotas { + return &memoryQuotas{windows: make(map[quotaWindowKey]*quotaWindowState), accounts: make(map[domain.MailProviderAccount]bool)} +} + +func (quotas *memoryQuotas) window(period domain.MailQuotaPeriod, windows domain.MailQuotaWindows) *quotaWindowState { + key := quotaWindowKey{period: period, start: windows.Start(period)} + if quotas.windows[key] == nil { + quotas.windows[key] = "aWindowState{} + } + return quotas.windows[key] +} + +func (quotas *memoryQuotas) used(period domain.MailQuotaPeriod, at time.Time) int64 { + return quotas.window(period, domain.MailQuotaWindowsAt(at)).used +} + +func (quotas *memoryQuotas) Reserve(_ context.Context, request outbound.MailQuotaReserveRequest) (outbound.MailQuotaReserveResult, error) { + reservation := request.Reservation + quotas.accounts[reservation.Account] = true + if !request.ReuseSince.IsZero() { + for index := len(quotas.journal) - 1; index >= 0; index-- { + entry := quotas.journal[index] + if entry.reservation.DeliveryID == reservation.DeliveryID && entry.reservation.Account == reservation.Account && + !entry.released && !entry.reservation.ReservedAt.Before(request.ReuseSince) { + return outbound.MailQuotaReserveResult{Reservation: entry.reservation, Reused: true}, nil + } + } + } + day := quotas.window(domain.MailQuotaPeriodDay, reservation.Windows) + month := quotas.window(domain.MailQuotaPeriodMonth, reservation.Windows) + check := outbound.MailQuotaCheck{ + DayExceeded: day.used+reservation.Recipients > request.Limits.Daily(), + MonthExceeded: month.used+reservation.Recipients > request.Limits.Monthly(), + } + if !check.Reserved() { + return outbound.MailQuotaReserveResult{Check: check}, nil + } + day.used += reservation.Recipients + month.used += reservation.Recipients + quotas.journal = append(quotas.journal, &journalEntry{reservation: reservation}) + return outbound.MailQuotaReserveResult{Check: check, Reservation: reservation}, nil +} + +func (quotas *memoryQuotas) Settle(_ context.Context, settlement outbound.MailQuotaSettlement) (bool, error) { + var entry *journalEntry + for _, candidate := range quotas.journal { + if candidate.reservation.ID == settlement.Reservation.ID { + entry = candidate + } + } + if entry == nil { + return false, domain.ErrInvalidMailQuota + } + released := false + if settlement.Release && !entry.released { + entry.released, released = true, true + for _, period := range []domain.MailQuotaPeriod{domain.MailQuotaPeriodDay, domain.MailQuotaPeriodMonth} { + window := quotas.window(period, entry.reservation.Windows) + if !window.providerExhausted { + window.used = max(window.used-entry.reservation.Recipients, 0) + } + } + } + entry.outcome = settlement.Outcome + if settlement.ExhaustedPeriod != "" { + window := quotas.window(settlement.ExhaustedPeriod, settlement.ExhaustedWindows) + window.used = max(window.used, settlement.ExhaustedLimit) + window.providerExhausted = true + } + return released, nil +} + +func (quotas *memoryQuotas) Usage(_ context.Context, _ domain.MailProviderAccount, windows domain.MailQuotaWindows) (outbound.MailQuotaUsage, error) { + return outbound.MailQuotaUsage{ + DayUsed: quotas.window(domain.MailQuotaPeriodDay, windows).used, + MonthUsed: quotas.window(domain.MailQuotaPeriodMonth, windows).used, + }, nil +} + +func (quotas *memoryQuotas) OtherAccountsWithUsage(context.Context, domain.MailProviderAccount, time.Time) ([]string, error) { + return []string{"old-label"}, nil +} + +type parkingDeliveries struct { + outbound.DeliveryRepository + + parked []domain.Delivery +} + +func (deliveries *parkingDeliveries) WaitForQuota(_ context.Context, next domain.Delivery) error { + deliveries.parked = append(deliveries.parked, next) + return nil +} + +type quotaUnit struct { + outbound.UnitOfWork + + quotas *memoryQuotas + deliveries *parkingDeliveries +} + +func (unit quotaUnit) MailQuotas() outbound.MailQuotaRepository { return unit.quotas } +func (unit quotaUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries } + +// quotaHarness drives a gate with a fake clock that tests move. +type quotaHarness struct { + now time.Time + unit quotaUnit + gate *QuotaGate + logs *bytes.Buffer +} + +const testIdempotencyWindow = 24 * time.Hour + +func newQuotaHarness(t *testing.T, provider string, daily, monthly int64, start time.Time) *quotaHarness { + t.Helper() + window := testIdempotencyWindow + if provider == "smtp" { + window = 0 + } + limits, err := domain.NewMailQuotaLimits(daily, monthly) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + h := "aHarness{ + now: start, + unit: quotaUnit{quotas: newMemoryQuotas(), deliveries: &parkingDeliveries{}}, + logs: &bytes.Buffer{}, + } + h.gate = NewQuotaGate(testAccount(t, provider), limits, window, func() time.Time { return h.now }, slog.New(slog.NewJSONHandler(h.logs, nil))) + return h +} + +func testAccount(t *testing.T, provider string) domain.MailProviderAccount { + t.Helper() + account, err := domain.NewMailProviderAccount(provider, "main") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + return account +} + +func quotaDelivery(t *testing.T, account domain.MailProviderAccount, createdAt time.Time) domain.Delivery { + t.Helper() + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", testSubject, testBody+"\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + recipient, err := domain.NewEmailAddress(testRecipientAddress) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), + RecipientUserID: uuid.Must(uuid.NewV7()), + Recipient: recipient, + Content: content, + ProviderAccount: account, + CreatedAt: createdAt, + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + return delivery +} + +func (h *quotaHarness) prepare(t *testing.T, delivery domain.Delivery) SendDecision { + t.Helper() + decision, err := h.gate.PrepareSend(t.Context(), h.unit, delivery) + if err != nil { + t.Fatalf("PrepareSend() error = %v", err) + } + return decision +} + +func (h *quotaHarness) settle(t *testing.T, permit QuotaPermit, result outbound.SendResult, sendErr error) time.Time { + t.Helper() + until, err := h.gate.SettleSend(t.Context(), h.unit, permit, result, sendErr) + if err != nil { + t.Fatalf("SettleSend() error = %v", err) + } + return until +} + +func (h *quotaHarness) assertUsage(t *testing.T, at time.Time, day, month int64) { + t.Helper() + if gotDay, gotMonth := h.unit.quotas.used(domain.MailQuotaPeriodDay, at), h.unit.quotas.used(domain.MailQuotaPeriodMonth, at); gotDay != day || gotMonth != month { + t.Fatalf("usage at %s = %d/%d, want %d/%d", at.Format(time.DateOnly), gotDay, gotMonth, day, month) + } +} + +func (h *quotaHarness) assertNoPersonalData(t *testing.T) { + t.Helper() + for _, marker := range privateMarkers { + if strings.Contains(h.logs.String(), marker) { + t.Fatalf("personal data %q reached the logs: %s", marker, h.logs.String()) + } + } +} + +func dailyQuotaAnswer(wait time.Duration) outbound.SendResult { + return outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, + ProviderCode: "daily_quota_exceeded", RetryAfter: wait, QuotaPeriod: domain.MailQuotaPeriodDay, + } +} + +func TestQuotaGateParksAtTheDailyLimitUntilMidnightUTC(t *testing.T) { + start := time.Date(2026, 10, 6, 22, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 3, 100, start) + account := testAccount(t, "resend") + for range 3 { + if decision := h.prepare(t, quotaDelivery(t, account, start)); !decision.Proceed() { + t.Fatal("a send within the daily limit was not admitted") + } + } + delivery := quotaDelivery(t, account, start) + decision := h.prepare(t, delivery) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + switch { + case decision.Proceed() || !decision.Permit.IsZero(): + t.Fatal("a send over the daily limit was admitted") + case !decision.ResetAt.Equal(midnight): + t.Fatalf("ResetAt = %s, want %s", decision.ResetAt, midnight) + case decision.Delivery.Status() != domain.DeliveryStatusWaitingQuota || !decision.Delivery.NextAttemptAt().Equal(midnight): + t.Fatalf("delivery is %s due %s, want waiting_quota due %s", decision.Delivery.Status(), decision.Delivery.NextAttemptAt(), midnight) + case len(h.unit.deliveries.parked) != 1 || h.unit.deliveries.parked[0].ID() != delivery.ID(): + t.Fatal("the waiting delivery was not stored") + } + h.assertUsage(t, start, 3, 3) + + // After midnight UTC the parked delivery is admitted again. + h.now = midnight + if retry := h.prepare(t, decision.Delivery); !retry.Proceed() { + t.Fatal("the waiting delivery was not admitted after the daily reset") + } + h.assertUsage(t, midnight, 1, 4) + h.assertNoPersonalData(t) +} + +func TestQuotaGateWaitsForTheMonthWhenTheMonthIsFull(t *testing.T) { + start := time.Date(2026, 12, 31, 23, 30, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 2, 2, start) + account := testAccount(t, "resend") + for range 2 { + h.prepare(t, quotaDelivery(t, account, start)) + } + decision := h.prepare(t, quotaDelivery(t, account, start)) + newYear := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC) + if decision.Proceed() || !decision.ResetAt.Equal(newYear) || !decision.Delivery.NextAttemptAt().Equal(newYear) { + t.Fatalf("decision = proceed %t, reset %s; want a wait until %s", decision.Proceed(), decision.ResetAt, newYear) + } + + // Both windows full in mid-month: the month reset wins over the day. + mid := time.Date(2027, 1, 15, 10, 0, 0, 0, time.UTC) + h = newQuotaHarness(t, "resend", 1, 1, mid) + h.prepare(t, quotaDelivery(t, account, mid)) + if decision := h.prepare(t, quotaDelivery(t, account, mid)); !decision.ResetAt.Equal(time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC)) { + t.Fatalf("ResetAt = %s, want the next month start", decision.ResetAt) + } +} + +func TestQuotaGateParksADeliveryChangedByAClockAhead(t *testing.T) { + now := time.Date(2026, 10, 6, 23, 59, 59, 998_000_000, time.UTC) + h := newQuotaHarness(t, "resend", 1, 100, now) + account := testAccount(t, "resend") + h.prepare(t, quotaDelivery(t, account, now)) + // Another instance, 5 ms ahead and already past midnight, created the + // delivery. + ahead := now.Add(5 * time.Millisecond) + delivery := quotaDelivery(t, account, ahead) + decision, err := h.gate.PrepareSend(t.Context(), h.unit, delivery) + if err != nil { + t.Fatalf("PrepareSend() for a delivery changed by a clock ahead error = %v", err) + } + stored := decision.Delivery + if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.UpdatedAt().Equal(ahead) || stored.NextAttemptAt().Before(ahead) { + t.Fatalf("parked delivery is %s, changed %s, due %s; want a change at %s and no due time before it", stored.Status(), stored.UpdatedAt(), stored.NextAttemptAt(), ahead) + } +} + +func TestQuotaGateHasNoBypassThroughAnotherTransport(t *testing.T) { + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + // The operator lowered the limit and switched to smtp: the same gate + // applies to the relay. + h := newQuotaHarness(t, "smtp", 1, 1, start) + smtp := testAccount(t, "smtp") + if !h.prepare(t, quotaDelivery(t, smtp, start)).Proceed() { + t.Fatal("the first SMTP send was not admitted") + } + if h.prepare(t, quotaDelivery(t, smtp, start)).Proceed() { + t.Fatal("an SMTP send over the lowered limit was admitted") + } + + // A delivery pinned to an account without a configured quota is never + // sent, rather than sent without a limit. + _, err := h.gate.PrepareSend(t.Context(), h.unit, quotaDelivery(t, testAccount(t, "resend"), start)) + if !errors.Is(err, ErrQuotaNotConfigured) { + t.Fatalf("PrepareSend() for another account error = %v, want ErrQuotaNotConfigured", err) + } + if h.unit.quotas.accounts[testAccount(t, "resend")] { + t.Fatal("a reservation was made for an account without a quota") + } +} + +func TestQuotaGateLeavesAnUnknownDeliveryToTheRetryPolicy(t *testing.T) { + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 1, 10, start) + account := testAccount(t, "resend") + h.prepare(t, quotaDelivery(t, account, start)) + unknown, _, err := quotaDelivery(t, account, start).RecordAttempt(domain.DeliveryAttemptInput{At: start, Outcome: domain.DeliveryOutcomeUnknown}) + if err != nil { + t.Fatalf("RecordAttempt() error = %v", err) + } + decision := h.prepare(t, unknown) + if decision.Proceed() || decision.Delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() { + t.Fatalf("decision for an unknown delivery: proceed %t, status %s, reset %s", decision.Proceed(), decision.Delivery.Status(), decision.ResetAt) + } + if len(h.unit.deliveries.parked) != 0 { + t.Fatal("an unknown delivery was parked in waiting_quota") + } + + accepted, _, err := quotaDelivery(t, account, start).RecordAttempt(domain.DeliveryAttemptInput{ + At: start, Outcome: domain.DeliveryOutcomeAccepted, ProviderMessageID: "message-1", + }) + if err != nil { + t.Fatalf("RecordAttempt() error = %v", err) + } + if _, err := h.gate.PrepareSend(t.Context(), h.unit, accepted); !errors.Is(err, domain.ErrDeliveryTransition) { + t.Fatalf("PrepareSend() for an accepted delivery error = %v, want ErrDeliveryTransition", err) + } +} + +func TestQuotaGateReusesTheReservationOfARetryInsideTheIdempotencyWindow(t *testing.T) { + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 2, 100, start) + account := testAccount(t, "resend") + delivery := quotaDelivery(t, account, start) + first := h.prepare(t, delivery) + h.settle(t, first.Permit, outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil) + + // The retry an hour later reuses the counted reservation, even with the + // day otherwise full. + h.prepare(t, quotaDelivery(t, account, start)) + h.now = start.Add(time.Hour) + retry := h.prepare(t, delivery) + if !retry.Proceed() || !retry.Permit.Reused() { + t.Fatalf("retry: proceed %t, reused %t; want the earlier reservation reused", retry.Proceed(), retry.Permit.Reused()) + } + h.assertUsage(t, start, 2, 2) + + // A rejection of the retry keeps the reservation: the first attempt may + // have been sent. + h.settle(t, retry.Permit, outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}, nil) + h.assertUsage(t, start, 2, 2) + + // After the window the provider no longer deduplicates, so a retry + // counts again: the next day has room. + h.now = start.Add(testIdempotencyWindow + time.Minute) + late := h.prepare(t, delivery) + if !late.Proceed() || late.Permit.Reused() { + t.Fatalf("late retry: proceed %t, reused %t; want a new reservation", late.Proceed(), late.Permit.Reused()) + } + h.assertUsage(t, h.now, 1, 3) +} + +func TestQuotaGateCountsEveryRetryWithoutProviderDeduplication(t *testing.T) { + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "smtp", 10, 100, start) + delivery := quotaDelivery(t, testAccount(t, "smtp"), start) + first := h.prepare(t, delivery) + h.settle(t, first.Permit, outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil) + if retry := h.prepare(t, delivery); retry.Permit.Reused() { + t.Fatal("an SMTP retry reused a reservation although SMTP has no deduplication") + } + h.assertUsage(t, start, 2, 2) +} + +func TestQuotaGateSettleSend(t *testing.T) { + start := time.Date(2026, 10, 6, 21, 0, 0, 0, time.UTC) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + nextMonth := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + tests := []struct { + name string + result outbound.SendResult + sendErr error + wantUntil time.Time + wantDay int64 + wantMonth int64 + }{ + {name: "accepted counts", result: outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: "m"}, wantDay: 1, wantMonth: 1}, + {name: "unknown counts", result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, wantDay: 1, wantMonth: 1}, + {name: "temporary rejection is released", result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}}, + {name: "permanent rejection is released", result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionPermanent}}, + {name: "rate limit is released", result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: time.Minute}}, + {name: "channel unavailable is released", sendErr: outbound.ErrMailChannelUnavailable}, + {name: "context ended before the send is released", sendErr: context.Canceled}, + {name: "daily provider quota marks the day until midnight", result: dailyQuotaAnswer(3 * time.Hour), wantUntil: midnight, wantDay: 100}, + { + name: "monthly provider quota marks the month until its end", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, QuotaPeriod: domain.MailQuotaPeriodMonth}, + wantUntil: nextMonth, wantMonth: 3000, + }, + { + name: "a quota answer without a window parks only the delivery for its hint", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, RetryAfter: 5 * time.Hour}, + wantUntil: start.Add(5 * time.Hour), + }, + { + name: "a quota answer without a window or hint waits for an operator", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted}, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + h := newQuotaHarness(t, "resend", 100, 3000, start) + decision := h.prepare(t, quotaDelivery(t, testAccount(t, "resend"), start)) + if until := h.settle(t, decision.Permit, test.result, test.sendErr); !until.Equal(test.wantUntil) { + t.Fatalf("SettleSend() until = %s, want %s", until, test.wantUntil) + } + h.assertUsage(t, start, test.wantDay, test.wantMonth) + h.assertNoPersonalData(t) + }) + } + + t.Run("a settlement needs the permit and an outcome", func(t *testing.T) { + h := newQuotaHarness(t, "resend", 100, 3000, start) + if _, err := h.gate.SettleSend(t.Context(), h.unit, QuotaPermit{}, outbound.SendResult{Outcome: outbound.MailOutcomeAccepted}, nil); !errors.Is(err, ErrInvalidQuotaPermit) { + t.Fatalf("SettleSend() without a permit error = %v, want ErrInvalidQuotaPermit", err) + } + decision := h.prepare(t, quotaDelivery(t, testAccount(t, "resend"), start)) + if _, err := h.gate.SettleSend(t.Context(), h.unit, decision.Permit, outbound.SendResult{}, nil); !errors.Is(err, ErrInvalidQuotaPermit) { + t.Fatalf("SettleSend() without an outcome error = %v, want ErrInvalidQuotaPermit", err) + } + }) + + t.Run("a repeated settlement releases once", func(t *testing.T) { + h := newQuotaHarness(t, "resend", 100, 3000, start) + account := testAccount(t, "resend") + h.prepare(t, quotaDelivery(t, account, start)) + decision := h.prepare(t, quotaDelivery(t, account, start)) + for range 2 { + h.settle(t, decision.Permit, outbound.SendResult{}, context.Canceled) + } + h.assertUsage(t, start, 1, 1) + }) + + t.Run("a release does not reopen a window the provider reported full", func(t *testing.T) { + h := newQuotaHarness(t, "resend", 100, 3000, start) + account := testAccount(t, "resend") + pending := h.prepare(t, quotaDelivery(t, account, start)) + refused := h.prepare(t, quotaDelivery(t, account, start)) + h.settle(t, refused.Permit, dailyQuotaAnswer(3*time.Hour), nil) + h.settle(t, pending.Permit, outbound.SendResult{}, context.Canceled) + h.assertUsage(t, start, 100, 0) + if h.prepare(t, quotaDelivery(t, account, start)).Proceed() { + t.Fatal("a send was admitted after the provider reported the day full") + } + }) +} + +func TestQuotaGateMarksTheWindowCurrentWhenTheProviderAnswers(t *testing.T) { + account := func(t *testing.T) domain.MailProviderAccount { + t.Helper() + return testAccount(t, "resend") + } + + t.Run("a daily refusal on the last day of the month marks only the day", func(t *testing.T) { + lastDay := time.Date(2026, 10, 31, 21, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 100, 3000, lastDay) + decision := h.prepare(t, quotaDelivery(t, account(t), lastDay)) + until := h.settle(t, decision.Permit, dailyQuotaAnswer(3*time.Hour), nil) + if !until.Equal(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)) { + t.Fatalf("until = %s, want November 1 00:00 UTC", until) + } + h.assertUsage(t, lastDay, 100, 0) + h.now = until + if !h.prepare(t, quotaDelivery(t, account(t), until)).Proceed() { + t.Fatal("the new month was blocked by a daily refusal") + } + }) + + t.Run("a reservation before midnight settled after it marks the new day", func(t *testing.T) { + reservedAt := time.Date(2026, 10, 6, 23, 59, 59, 0, time.UTC) + h := newQuotaHarness(t, "resend", 100, 3000, reservedAt) + decision := h.prepare(t, quotaDelivery(t, account(t), reservedAt)) + h.now = time.Date(2026, 10, 7, 0, 0, 0, 5_000_000, time.UTC) + until := h.settle(t, decision.Permit, dailyQuotaAnswer(24*time.Hour), nil) + if !until.Equal(time.Date(2026, 10, 8, 0, 0, 0, 0, time.UTC)) { + t.Fatalf("until = %s, want October 8 00:00 UTC", until) + } + // The reservation was released from October 6 and the month; only + // October 7 is full. + h.assertUsage(t, reservedAt, 0, 0) + if day := h.unit.quotas.used(domain.MailQuotaPeriodDay, h.now); day != 100 { + t.Fatalf("usage of the new day = %d, want 100", day) + } + }) + + t.Run("a provider clock a few milliseconds ahead does not move the window", func(t *testing.T) { + now := time.Date(2026, 10, 6, 23, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 100, 3000, now) + decision := h.prepare(t, quotaDelivery(t, account(t), now)) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + // The hint was computed by a clock 5 ms ahead of ours. + until := h.settle(t, decision.Permit, dailyQuotaAnswer(midnight.Sub(now.Add(5*time.Millisecond))), nil) + if !until.Equal(midnight) { + t.Fatalf("until = %s, want %s", until, midnight) + } + h.assertUsage(t, now, 100, 0) + }) +} + +func TestReportQuotaUsageWarnsAboutOtherAccounts(t *testing.T) { + now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + h := newQuotaHarness(t, "resend", 100, 3000, now) + h.prepare(t, quotaDelivery(t, testAccount(t, "resend"), now)) + limits, err := domain.NewMailQuotaLimits(100, 3000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + logs := &bytes.Buffer{} + if err := ReportQuotaUsage(t.Context(), h.unit.quotas, testAccount(t, "resend"), limits, now, slog.New(slog.NewJSONHandler(logs, nil))); err != nil { + t.Fatalf("ReportQuotaUsage() error = %v", err) + } + for _, want := range []string{`"msg":"mail quota usage"`, `"day_used":1`, `"month_limit":3000`, `"other_accounts":["old-label"]`, `"level":"WARN"`} { + if !strings.Contains(logs.String(), want) { + t.Fatalf("report lacks %s: %s", want, logs.String()) + } + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index bbffdcb..6c3c7f5 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -191,6 +191,10 @@ services: EMAIL_FROM: ${EMAIL_FROM:?Set EMAIL_FROM in the root .env file} EMAIL_ACCOUNT: ${EMAIL_ACCOUNT:-default} EMAIL_TIMEOUT: ${EMAIL_TIMEOUT:-10s} + # Empty means unset: the backend applies the Resend Free defaults for + # resend and refuses to start smtp without stated limits. + EMAIL_QUOTA_DAILY: ${EMAIL_QUOTA_DAILY:-} + EMAIL_QUOTA_MONTHLY: ${EMAIL_QUOTA_MONTHLY:-} APP_PUBLIC_URL: ${APP_PUBLIC_URL:?Set APP_PUBLIC_URL in the root .env file} RESEND_API_KEY: ${RESEND_API_KEY:-} SMTP_HOST: ${SMTP_HOST:-} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 02019b8..362c34a 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -162,7 +162,7 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai - `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`. - `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator. -`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store. +`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store. A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. @@ -180,19 +180,19 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt | 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates | | 409 without a known name | `unknown` | | 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` | -| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` until the next 00:00 UTC | -| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, no `RetryAfter`: the reset follows the billing cycle | +| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` until the next 00:00 UTC | +| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, no `RetryAfter`: the reset follows the billing cycle | | 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` | | Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed | | No answer after the request was written: timeout, reset, or closed connection | `unknown` | | Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend | | The caller's context ended before the request was written | the context error; nothing was sent | -Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, waiting for a quota reset or an operator decision, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer. +Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). ### Mail deliveries -Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. Planned: the worker that claims due deliveries and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), quotas (TASK-018), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery. +Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery. A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: @@ -231,7 +231,7 @@ Statuses. The values follow the `MailSender` outcomes: | `accepted` | The provider accepted the message and returned `provider_message_id`; not delivery to or reading by a person | None; terminal | | `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal | | `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": a retry reuses the key and the stored body | Optional; none means no automatic retry | -| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset; none when the reset is unknown, for example Resend's monthly quota, and an operator or the quota rule decides | +| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides | Transitions: @@ -243,7 +243,7 @@ Every change advances `version`, and the store applies it only over the previous Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt. -Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. TASK-018 needs its own counter that does not cascade, keyed by provider, provider account, and UTC day or month, and incremented atomically when a send is admitted. +Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas). Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). TASK-016 uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision. @@ -252,10 +252,53 @@ Planned additive changes for later tasks. Each is a new column, index, or CHECK - A terminal cancelled status for a delivery that must not be sent anymore: a token or account invalidated before the send (TASK-016) or a revoked permission (TASK-462). - A nullable reference from a token mail delivery to `email_tokens.id`, so the worker can check that the token is still the active one for its purpose before it sends (TASK-016). - For the sending worker (TASK-016): lease columns (for example a claim owner and `claimed_until`) and a partial index on `next_attempt_at` for the statuses that are picked up again, so several processes claim due deliveries with `FOR UPDATE SKIP LOCKED` and an attempt whose process stopped after the request becomes `unknown`. -- The non-cascading quota counter of TASK-018 described above. The store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`. +### Mail quotas + +Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016), quota metrics (TASK-022), and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing. + +Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets. + +Tables. Neither table has a foreign key to users or deliveries: deleting an account deletes its deliveries and attempts by cascade, but the provider has already counted those messages, so the usage stays. Neither holds personal data; `delivery_id` is an opaque ID. + +- `mail_quota_usage`: one row per provider, provider account, period kind (`day` or `month`), and period start (a UTC date; the first day for a month), with `used_recipients`, `provider_exhausted_at`, and `updated_at`. An account accrues about 400 rows a year. +- `mail_quota_reservations`: a journal with one row per admitted send: the delivery, the account, the day and month windows it was counted in, the recipients, `reserved_at`, `released_at` (set once), and the last `settled_outcome` (`accepted`, `unknown`, `rejected`, or `not_sent`) with `settled_at`. A row without an outcome is a send in flight, or one whose process stopped before settling. A partial index serves the lookup of a delivery's open reservations. There is no retention rule for either table yet; journal rows are needed only within the reuse window and for the audit of a month. + +Lock order. Every write first creates and locks all the usage rows it will touch with one statement, sorted by `(period_kind, period_start)`, and only then updates them or the journal; later `UPDATE` statements find their rows locked already. The order therefore never depends on the query plan. An `UPDATE ... WHERE (day) OR (month)` alone locks rows in scan order, which with a bitmap or sequential scan is heap order, and deadlocked against a reservation that locked the day first; the integration test reproduces that interleaving and checks that it no longer deadlocks. A settlement that releases yesterday's windows and marks today's locks all three rows in the same sorted statement. The guarantee covers the quota rows only: a caller that also locks other rows in the same transaction, such as the delivery, keeps its own consistent order for them. + +Reservation. `QuotaGate.PrepareSend(ctx, unit, delivery)` runs in the caller's transaction: + +1. A delivery pinned to a provider account other than the configured one fails with `notification.ErrQuotaNotConfigured`: no limits are known for it, and an account without a quota is never "unlimited". An `accepted` or `rejected` delivery fails with `domain.ErrDeliveryTransition`. +2. A retry inside the provider's idempotency window reuses an open reservation of the same delivery (the earlier attempt was `unknown`, or its process stopped before settling) and proceeds without counting again: the provider answers a repeated key with the original result instead of sending twice. The window is a gate parameter: `resend.IdempotencyWindow`, 24 hours per the Resend API documentation, or zero for SMTP, which has no provider-side deduplication, so every SMTP retry counts again. After the window a retry counts again; whether it may run at all is the retry policy's decision (TASK-017). +3. Otherwise the repository locks the day and month rows, adds one recipient to both only when it fits both limits, and journals the reservation. If it does not fit, nothing changes and the result says which limit would be exceeded. The reservation is all-or-nothing across both windows. +4. When the send is admitted, the decision carries a permit and the delivery is unchanged. Otherwise the delivery waits for the reset of the full window: the next 00:00 UTC for the day, the first day of the next month for the month; when both are full, the month reset wins. A `pending` or `waiting_quota` delivery is stored as `waiting_quota` with `next_attempt_at` at that time through `Delivery.WaitForQuota`. The change time is the later of the clock and the delivery's last change, and the reset is not earlier than that, so an instance whose clock runs a few milliseconds behind the one that last wrote the delivery can still park it. An `unknown` delivery is returned unchanged with the reset time: its retry belongs to the retry policy (TASK-017), and parking it would hide that an earlier attempt may have been accepted. + +The row locks last until the caller's transaction ends, so the worker must commit before it calls the transport; the cost is that sends of one account reserve one after another. + +Settlement. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` runs in the transaction that stores the attempt or, after a `Send` error, the delivery's next state. It always journals the outcome, and: + +- `accepted` and `unknown` keep the reservation. An unknown attempt may have been sent, and counting it errs on the safe side. +- A `Send` error, where nothing left the process, and every `rejected` outcome release a new reservation: the provider did not take the message, so it did not count it. Without the release, a provider outage would use up the daily quota with failed retries. The journal sets `released_at` only on an open row, so a repeated settlement, for example after a commit whose answer was lost, releases nothing a second time, independently of the delivery's version. A reused reservation is never released: the earlier attempt under it may have been sent. A reservation that is never settled, for example after a crash between the two transactions, stays counted, which only over-counts. +- `rejected` with `quota_exhausted` also refines the count from the provider's answer. The window comes from `SendResult.QuotaPeriod`, which the transport fills from the provider's own error name (Resend `daily_quota_exceeded` gives `day`, `monthly_quota_exceeded` gives `month`), not from the wait hint. The window is the one current at settlement, because the provider answered about it, even when the reservation was made before midnight. The day mark raises that day's usage to the daily limit and the delivery waits for the next 00:00 UTC; the month mark raises the month's usage to the monthly limit and the delivery waits for the next UTC month start. A daily refusal on the last day of a month marks only the day. Resend's monthly quota follows the account's billing cycle; if that cycle resets later than the calendar month, the retry at the month start is refused again and waits another month unless an operator decides otherwise. Without a named window nothing is marked: the delivery waits for the provider's hint, or, without one, for an operator. A marked row records `provider_exhausted_at`, and a release no longer lowers it, so the local count stays at the provider's answer until the window resets. Raising the limit reopens the window; that is the operator's decision. `SettleSend` returns the time to store as the attempt's `next_attempt_at`. + +No purchase, plan switch, or transport change. The gate only defers. Nothing buys a plan, moves the account to a paid tier, or sends a waiting delivery through another transport, provider, or account; the delivery stays pinned (see [Mail deliveries](#mail-deliveries)). Switching `EMAIL_PROVIDER` is an operator decision, and the gate applies to the new transport too: it runs in the usecase before any transport is called, `smtp` needs stated limits, and deliveries pinned to the old account are refused instead of being sent without a limit. Counters are kept per provider and account label, so a new transport or a new `EMAIL_ACCOUNT` label starts with its own count. A transport that reaches the same provider account by another route, for example Resend's own SMTP endpoint, shares the provider's quota but not the local count, and so does a relabeled account: the provider's refusal then refines the count as above, the startup report warns about other labels with usage this month, and the operator should set the limits to what the account has left. + +Startup report. After the startup migrations, unless `EMAIL_PROVIDER=disabled`, bootstrap logs `mail quota usage` with the provider, account, and the day and month usage and limits, and warns `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count` when other account labels of the same provider have usage this month. A failed read is a warning and never stops startup. + +What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` returns the status of the newest delivery of a kind addressed to the account: the kind, the status, `WaitingUntil` for `waiting_quota` (the stored `next_attempt_at`), and the time of the last change. It returns no address, subject, body, provider, or delivery ID, and false when there is none. The query is scoped to deliveries addressed to the given account, so the caller must pass the authenticated account's own ID, never an ID from request input. No HTTP route calls it yet; the identity flows and a later API show it. A user interface maps the statuses as follows: + +| Status | What the user is told | +| --- | --- | +| `waiting_quota` with `WaitingUntil` | Your email is waiting until `` | +| `waiting_quota` without `WaitingUntil` | Your email is waiting; the time is not known yet | +| `pending`, `unknown` | Your email is being sent. `unknown` is not shown as a failure: the message may have been accepted | +| `accepted` | Your email was sent. It means that the provider accepted it, not that it reached the inbox | +| `rejected` | Your email could not be sent | + +Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. There is no quota metric yet; `MailQuotaRepository.Usage` is the read that TASK-022 can expose with the labels provider and period. + ### Product policy versions Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 81aa5b1..83d9a92 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -168,7 +168,7 @@ The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects e Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. No flow sends mail yet: mail requests are stored as deliveries (see [Mail deliveries](#mail-deliveries)), and the worker that calls the transport is planned. -`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, waiting for a daily or monthly quota reset, and outcome records belong to the planned delivery layer. Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). +`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). `disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. @@ -176,8 +176,10 @@ Current state: this build contains the `disabled` and `resend` transports. With | --- | --- | --- | | `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive | | `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex `. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. | -| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. | +| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to and that the quota is counted under: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. Change it only with a real account change; renaming it resets the local quota count. | | `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | +| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. | +| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. | | `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | | `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | | `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. | @@ -185,7 +187,7 @@ Current state: this build contains the `disabled` and `resend` transports. With | `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. | | `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. | -Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. +Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. ### Mail deliveries @@ -194,9 +196,22 @@ A notification request is a row in `mail_requests` until the consumer `notificat - Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created while `EMAIL_PROVIDER=disabled` stay pinned to `disabled` until the sending worker (TASK-016) moves them with `Rebind`, which is allowed only before the first attempt. - The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet. - To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats. -- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` without `next_attempt_at` waits for a quota reset that is not known, such as Resend's monthly quota, and needs an operator decision. +- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision. - Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request. +### Mail quotas + +Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The quota gate is implemented, but the sending worker that calls it is planned (TASK-016), so the current build counts nothing yet. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). + +- Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart. +- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month. +- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet. +- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`. +- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused. +- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan. +- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017). +- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit. + ### Mail templates Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery; registration, verification, password reset, and sending are planned, so the current build sends no message. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 33fe61c..be39549 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -57,7 +57,7 @@ What exists now: - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), and the mail delivery tables (`deliveries`, `delivery_attempts`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), and the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -197,6 +197,8 @@ A directly launched backend with a registered handler and `DATABASE_URL` set con To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests). +Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index a29cf59..1fa933a 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -131,7 +131,43 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa - A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID. - The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it. -Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, quotas, and the permission check are later tasks, and there is no test of a verification or password reset delivery, which the identity flows will create. +Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, and the permission check are later tasks, quotas have their own [Mail quota tests](#mail-quota-tests), and there is no test of a verification or password reset delivery, which the identity flows will create. + +## Mail quota tests + +Unit tests (`make -C backend test`) cover the quota rules without a database: + +- `internal/domain/`: the day and month windows of an instant are UTC calendar periods whatever its location: midnight UTC belongs to the new day and one nanosecond before it to the old one, a local time after local midnight can still be the previous UTC day, the day reset of February 28 in a common year and of February 29 in a leap year is March 1, and December resets into January of the next year; limits refuse zero, negative, and a daily limit above the monthly one. +- `config/` and `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` default to 100 and 3000 for `resend` and `disabled`; `smtp` refuses to start without either and takes stated values; a lowered value is taken as configured for every provider; an empty value counts as unset; zero, negative, non-integer, out-of-range values and a daily limit above the monthly one are refused without echoing secrets; bootstrap refuses to start with a quota of zero. +- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` gives `QuotaPeriod` `day` with the wait until midnight, and `monthly_quota_exceeded` gives `month` without a wait. +- `internal/usecase/notification/`, with an in-memory counter and journal and a fake clock: + - `QuotaGate.PrepareSend` admits sends up to the daily limit and parks the next one in `waiting_quota` until 00:00 UTC without counting it, then admits it after midnight. It waits for the month start when the month is full (December 31 to January 1) and also when both windows are full. + - It parks a delivery last changed by an instance whose clock is 5 ms ahead, past midnight, at that change time without an error. + - It applies a lowered limit to `smtp` like any other transport, and refuses a delivery pinned to an account without a quota, reserving nothing for it. + - It returns an `unknown` delivery unchanged with the reset time and refuses a terminal one. + - A retry within 24 hours reuses the open reservation even with the day otherwise full; a rejection of that retry keeps it; after the window the retry counts again. An `smtp` gate, without provider deduplication, counts every retry. + - `SettleSend` keeps the reservation for `accepted` and `unknown`, and releases it for a `Send` error and every `rejected` outcome. A repeated settlement releases once. + - A daily quota answer marks the day and returns midnight, a monthly one marks the month and returns its end, an answer without a window parks only the delivery for its hint or without a time, and a window the provider reported full is not reopened by a release. + - The window marked is the one current at settlement: a daily refusal on October 31 marks only the day and leaves November open, a reservation at 23:59:59 settled 5 ms after midnight marks the new day, and a hint computed by a provider clock 5 ms ahead still gives exactly midnight. + - `ReportQuotaUsage` logs the usage and limits and warns with the other account labels. + - `DeliveryStatusReader.LatestForUser` returns the kind, status, and change time, and `WaitingUntil` only for `waiting_quota`. It asks only for the given account, returns nothing without a delivery, and refuses a nil account and an unknown kind. + - Logs hold no address, subject, or body. + +`TestMailQuota` in `backend/integration_test/mail_quota_test.go` uses `bootstrap(t, postgresService)`, the real transactor, delivery store, and quota repository, and a fake clock. Each case starts from empty tables: + +- Concurrency: 12 senders, each with its own connection and transaction, call `PrepareSend` at once. On windows without rows (the row creation races too) and a daily limit of 10 exactly 10 get a permit; after 7 sequential sends exactly 3 of the next 12 get one. Every other delivery is stored as `waiting_quota` with `next_attempt_at` at the next 00:00 UTC, and both counters end at 10. Without the row lock the case fails with all 12 admitted. +- Midnight and month boundary: with limits of 2 per day and 3 per month starting October 30 at 22:00 UTC, the third send waits until October 31 00:00 UTC, still waits one second before it, and goes at midnight; the fourth waits for November 1 because the month is full, and goes then. The day and month rows hold 2, 1, 1 and 3, 1. +- Lowered limit and SMTP: gates are built from `config.LoadFromEnv`. After 4 Resend sends with the default limit, a limit lowered to 3 parks the next send until midnight. `smtp` without quota settings fails to load; with 2 and 2 it admits two relay sends and parks the third until the month start, and a Resend delivery under the `smtp` gate fails with `ErrQuotaNotConfigured` and changes no counter. +- Provider refinement: a `temporary` rejection gives its reservation back. A `daily_quota_exceeded` refusal while the local count is 1 of 100 stores the delivery as `waiting_quota` until midnight with one attempt, raises the day row to 100 with `provider_exhausted_at`, and the gate then parks the next delivery itself. After midnight a `monthly_quota_exceeded` refusal raises the month row to 3000 and parks the deliveries until November 1. +- Account deletion: three accepted sends count 3 of 3; deleting the account deletes its deliveries and attempts by cascade, the counters keep 3, and a delivery for another account the same day waits until midnight. +- Lock order, deterministic: the month row lies before the day row in the heap, and the writers run on sessions with `enable_indexscan=off`, so scans follow heap order as in the reproduced deadlock. A third transaction holds the day row; a reservation and a release queue on it in both orders, and the blocker is released. Neither gets a deadlock error, and the usage ends consistent. With the ordered lock removed from `Settle`, the case fails with SQLSTATE 40P01. +- Lock order, bounded stress: 60 rounds, each starting at once a release of day two, a release of day one that marks day two across midnight, and two reservations of day two, on heap-order sessions. No round returns an error. +- Journal: a transport error settled twice releases once. An unknown attempt's reservation is reused by a retry an hour later and not after the 24-hour window. The journal ends with 2 open rows, 1 released, and 2 with an outcome. +- User status: an account without mail gets nothing; after one admitted and one parked notification it sees `waiting_quota` until midnight; another account and another kind get nothing. +- Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`. +- The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome. + +`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The suite does not call a transport: the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is TASK-016. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 896fa5c..5ebb4c3 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -162,7 +162,7 @@ Offsets и партиции. Каждый обработчик - один уча - `rejected`: провайдер не принял письмо. Либо он ответил отказом, либо транспорт сломался до полной записи запроса (DNS, соединение или TLS), и полный запрос до провайдера не дошел; второй случай всегда `temporary`, и повтор не может продублировать письмо. `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`. - `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Дедупликация у провайдера ограничена окном (24 часа у Resend); после него повтор может отправить письмо дважды, поэтому слой доставки обязан прекратить повторы и передать случай оператору. -`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить. +`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить. Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. @@ -180,19 +180,19 @@ Offsets и партиции. Каждый обработчик - один уча | 409 `invalid_idempotent_request` | `unknown`: ключ уже использован с другим телом, поэтому более ранний запрос мог быть принят; повтор не поможет, и слой доставки останавливается и передает случай оператору | | 409 без известного имени | `unknown` | | 429 `rate_limit_exceeded` или без имени | `rejected`, `rate_limited`, `RetryAfter` из `Retry-After` (секунды или будущая HTTP-дата), иначе из `ratelimit-reset` | -| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` до ближайших 00:00 UTC | -| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, без `RetryAfter`: сброс зависит от платежного цикла | +| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` до ближайших 00:00 UTC | +| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, без `RetryAfter`: сброс зависит от платежного цикла | | 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` из `Retry-After` | | Прочие 5xx, включая 500 `application_error` и `internal_server_error`, обрезанное тело или ответ прокси или шлюза | `unknown`: API мог принять письмо до сбоя | | Нет ответа после записи запроса: таймаут, сброс или закрытие соединения | `unknown` | | Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел | | Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено | -Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit, ожидание сброса квоты или решения оператора, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки. +Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты). ### Доставки писем -Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Запланировано: worker, который берет доставки к отправке и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), квоты (TASK-018), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет. +Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет. Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит: @@ -231,7 +231,7 @@ Offsets и партиции. Каждый обработчик - один уча | `accepted` | Провайдер принял письмо и вернул `provider_message_id`; это не доставка человеку и не прочтение | Нет; конечный | | `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный | | `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет | -| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс; отсутствует, когда момент сброса неизвестен, например для месячной квоты Resend, и решение принимает оператор или правило квот | +| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор | Переходы: @@ -243,7 +243,7 @@ Offsets и партиции. Каждый обработчик - один уча Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки. -Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. TASK-018 нужен собственный счетчик без каскада, с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца, который атомарно увеличивается при допуске отправки. +Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. Поэтому у квоты собственный счетчик без каскада с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца; см. [Квоты почты](#квоты-почты). Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача. @@ -252,10 +252,53 @@ Offsets и партиции. Каждый обработчик - один уча - Конечный статус отмены для доставки, которую больше нельзя отправлять: токен или аккаунт аннулирован до отправки (TASK-016) или отозвано разрешение (TASK-462). - Необязательная ссылка доставки письма с токеном на `email_tokens.id`, чтобы worker перед отправкой проверил, что токен все еще действующий для своего назначения (TASK-016). - Для worker отправки (TASK-016): столбцы lease (например, владелец захвата и `claimed_until`) и частичный индекс по `next_attempt_at` для статусов, которые берутся снова, чтобы несколько процессов захватывали доставки через `FOR UPDATE SKIP LOCKED`, а попытка, процесс которой остановился после отправки запроса, становилась `unknown`. -- Описанный выше счетчик квот TASK-018 без каскада. Хранилище уже дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota` и `Rebind`. +### Квоты почты + +Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Запланировано: worker отправки, который вызывает шлюз вокруг `MailSender.Send` и собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP (TASK-016), метрики квот (TASK-022) и API или сценарий identity, который показывает результат чтения статуса. Пока ничего не отправляется, поэтому текущая сборка ничего не считает. + +Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна. + +Таблицы. Внешних ключей на пользователей или доставки нет ни у одной: удаление аккаунта каскадно удаляет его доставки и попытки, но провайдер эти письма уже посчитал, поэтому расход остается. Персональных данных нет ни в одной; `delivery_id` - непрозрачный ID. + +- `mail_quota_usage`: одна строка на провайдер, аккаунт провайдера, вид периода (`day` или `month`) и начало периода (дата UTC; для месяца первое число) с полями `used_recipients`, `provider_exhausted_at` и `updated_at`. На один аккаунт набирается около 400 строк в год. +- `mail_quota_reservations`: журнал с одной строкой на допущенную отправку: доставка, аккаунт, окна суток и месяца, в которых она посчитана, число получателей, `reserved_at`, `released_at` (ставится один раз) и последний `settled_outcome` (`accepted`, `unknown`, `rejected` или `not_sent`) с `settled_at`. Строка без исхода - отправка в процессе или такая, чей процесс остановился до расчета. Частичный индекс обслуживает поиск открытых резервирований доставки. Правила хранения пока нет ни для одной таблицы; строки журнала нужны только в окне повторного использования и для аудита месяца. + +Порядок блокировок. Каждая запись сначала одним запросом создает и блокирует все строки расхода, которые она затронет, в порядке `(period_kind, period_start)`, и только потом обновляет их или журнал; следующие `UPDATE` находят свои строки уже заблокированными. Поэтому порядок никогда не зависит от плана запроса. Одиночный `UPDATE ... WHERE (day) OR (month)` блокирует строки в порядке сканирования, а при bitmap или последовательном сканировании это порядок в heap, и такой запрос попадал во взаимоблокировку с резервированием, которое блокировало сначала сутки; интеграционный тест воспроизводит это чередование и проверяет, что взаимоблокировки больше нет. Расчет, который возвращает вчерашние окна и отмечает сегодняшние, блокирует все три строки тем же отсортированным запросом. Гарантия касается только строк квот: вызывающий, который в той же транзакции блокирует другие строки, например доставку, сам соблюдает для них единый порядок. + +Резервирование. `QuotaGate.PrepareSend(ctx, unit, delivery)` выполняется в транзакции вызывающего: + +1. Доставка, закрепленная за другим аккаунтом провайдера, чем настроенный, завершается ошибкой `notification.ErrQuotaNotConfigured`: лимиты для нее неизвестны, а аккаунт без квоты никогда не считается "безлимитным". Доставка в `accepted` или `rejected` завершается ошибкой `domain.ErrDeliveryTransition`. +2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов (TASK-017). +3. Иначе репозиторий блокирует строки суток и месяца, добавляет одного получателя в обе, только если он укладывается в оба лимита, и записывает резервирование в журнал. Если не укладывается, ничего не меняется, а результат сообщает, какой лимит был бы превышен. Резервирование выполняется по обоим окнам целиком или не выполняется вовсе. +4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов (TASK-017), а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята. + +Блокировки строк держатся до конца транзакции вызывающего, поэтому worker обязан зафиксировать транзакцию до вызова транспорта; цена - отправки одного аккаунта резервируются по очереди. + +Расчет. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` выполняется в транзакции, которая сохраняет попытку, а после ошибки `Send` - следующее состояние доставки. Он всегда записывает исход в журнал, а кроме того: + +- `accepted` и `unknown` оставляют резервирование. Неизвестная попытка могла быть отправлена, и учет ее в расходе ошибается в безопасную сторону. +- Ошибка `Send`, когда ничего не покинуло процесс, и любой исход `rejected` возвращают новое резервирование: провайдер письмо не взял и не посчитал. Без возврата сбой провайдера израсходовал бы суточную квоту на неудачные повторы. Журнал ставит `released_at` только в открытой строке, поэтому повторный расчет, например после commit, ответ на который потерялся, второй раз ничего не возвращает, и это не зависит от версии доставки. Повторно использованное резервирование не возвращается никогда: прошлая попытка под ним могла быть отправлена. Резервирование, которое так и не рассчитано, например после падения между двумя транзакциями, остается в расходе; это дает только завышенный счет. +- `rejected` с `quota_exhausted` еще и уточняет счет по ответу провайдера. Окно берется из `SendResult.QuotaPeriod`, которое транспорт заполняет по собственному имени ошибки провайдера (Resend `daily_quota_exceeded` дает `day`, `monthly_quota_exceeded` - `month`), а не из подсказки ожидания. Окно берется текущее на момент расчета, потому что провайдер ответил именно о нем, даже если резервирование было сделано до полуночи. Отметка суток поднимает расход этих суток до суточного лимита, и доставка ждет ближайших 00:00 UTC; отметка месяца поднимает расход месяца до месячного лимита, и доставка ждет начала следующего месяца UTC. Суточный отказ в последний день месяца отмечает только сутки. Месячная квота Resend следует платежному циклу аккаунта; если цикл сбрасывается позже календарного месяца, повтор в начале месяца снова получит отказ и будет ждать еще месяц, если оператор не решит иначе. Без названного окна ничего не отмечается: доставка ждет по подсказке провайдера, а без нее - решения оператора. В отмеченной строке фиксируется `provider_exhausted_at`, и возврат больше не уменьшает ее, поэтому локальный счет остается на значении из ответа провайдера до сброса окна. Повышение лимита снова открывает окно; это решение оператора. `SettleSend` возвращает момент, который нужно сохранить как `next_attempt_at` попытки. + +Без покупки, смены тарифа и транспорта. Шлюз только откладывает. Ничто не покупает тариф, не переводит аккаунт на платный план и не отправляет ожидающую доставку через другой транспорт, провайдера или аккаунт; доставка остается закрепленной (см. [Доставки писем](#доставки-писем)). Смена `EMAIL_PROVIDER` - решение оператора, и шлюз действует и для нового транспорта: он работает в usecase до вызова любого транспорта, `smtp` требует явно заданных лимитов, а доставки, закрепленные за прежним аккаунтом, отклоняются, а не отправляются без лимита. Счетчики ведутся по провайдеру и метке аккаунта, поэтому новый транспорт или новая метка `EMAIL_ACCOUNT` начинают со своего счета. Транспорт, который другим путем ведет в тот же аккаунт провайдера, например собственный SMTP-адрес Resend, делит квоту провайдера, но не локальный счет, и так же ведет себя переименованная метка аккаунта: отказ провайдера тогда уточняет счет, как описано выше, отчет при запуске предупреждает о других метках с расходом в этом месяце, а оператору стоит задать лимиты по остатку аккаунта. + +Отчет при запуске. После миграций при запуске, кроме `EMAIL_PROVIDER=disabled`, bootstrap пишет в журнал `mail quota usage` с провайдером, аккаунтом, расходом и лимитами суток и месяца и предупреждает `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count`, если у других меток аккаунта того же провайдера есть расход в этом месяце. Неудачное чтение дает предупреждение и никогда не останавливает запуск. + +Что видит пользователь. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` возвращает статус новейшей доставки вида, адресованной аккаунту: вид, статус, `WaitingUntil` для `waiting_quota` (сохраненный `next_attempt_at`) и время последнего изменения. Адрес, тему, тело, провайдера и ID доставки он не возвращает, а если доставки нет, возвращает false. Запрос ограничен доставками указанному аккаунту, поэтому вызывающий обязан передавать ID самого аутентифицированного аккаунта и никогда не брать его из входных данных запроса. HTTP-маршрута, который его вызывает, пока нет; результат покажут сценарии identity и следующее API. Интерфейс показывает статусы так: + +| Статус | Что видит пользователь | +| --- | --- | +| `waiting_quota` с `WaitingUntil` | Ваше письмо ожидает отправки до `` | +| `waiting_quota` без `WaitingUntil` | Ваше письмо ожидает отправки; время пока неизвестно | +| `pending`, `unknown` | Ваше письмо отправляется. `unknown` не показывается как сбой: письмо могло быть принято | +| `accepted` | Ваше письмо отправлено. Это значит, что провайдер его принял, а не что оно дошло до ящика | +| `rejected` | Ваше письмо не удалось отправить | + +Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Метрик квот пока нет; `MailQuotaRepository.Usage` - чтение, которое TASK-022 может отдать с метками provider и period. + ### Версии продуктовой политики Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 7af1fbc..cea8d5b 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -170,7 +170,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Пока ни один сценарий не отправляет почту: запросы писем сохраняются как доставки (см. [Доставки писем](#доставки-писем)), а worker, который вызывает транспорт, запланирован. -`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit, ожидание сброса дневной или месячной квоты и учет результатов относятся к запланированному слою доставки. Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). +`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов относятся к запланированному слою доставки, а ожидание сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). `disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`. @@ -178,8 +178,10 @@ Backend отправляет почту через порт `MailSender`. `EMAIL | --- | --- | --- | | `EMAIL_PROVIDER` | нет, обязательна | `resend`, `smtp` или `disabled`, без учета регистра | | `EMAIL_FROM` | нет, обязательна | Один mailbox: `no-reply@example.com` или `Lincodex `. Только печатные ASCII символы. Адрес подчиняется правилам адресов аккаунтов: local part без кавычек и DNS-домен минимум из двух меток, без IP literal. | -| `EMAIL_ACCOUNT` | `default` | Метка аккаунта провайдера, за которым закрепляются новые доставки: от 1 до 64 строчных букв, цифр, `.`, `_` или `-`, начиная с буквы или цифры. Никогда не ключ. | +| `EMAIL_ACCOUNT` | `default` | Метка аккаунта провайдера, за которым закрепляются новые доставки и под которой ведется счет квоты: от 1 до 64 строчных букв, цифр, `.`, `_` или `-`, начиная с буквы или цифры. Никогда не ключ. Меняйте ее только при настоящей смене аккаунта; переименование сбрасывает локальный счет квоты. | | `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта | +| `EMAIL_QUOTA_DAILY` | `100` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за UTC-сутки через настроенный аккаунт провайдера: целое от 1 до 1000000000. Пустое значение считается незаданным. Значения, которое отключает квоту, нет. | +| `EMAIL_QUOTA_MONTHLY` | `3000` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за календарный месяц UTC: целое от 1 до 1000000000, не меньше `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. | | `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | | `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. | | `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. | @@ -187,7 +189,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL | `SMTP_USERNAME`, `SMTP_PASSWORD` | пусто | Обязательны для `smtp`; анонимный relay не поддерживается. | | `SMTP_TLS_MODE` | пусто | Обязательна для `smtp`. `starttls` (переход на TLS через STARTTLS, обычно порт 587) или `tls` (TLS с начала соединения, обычно порт 465). SMTP без шифрования не поддерживается. | -Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера. +Compose передает эти переменные из корневого `.env`; незаданные `EMAIL_QUOTA_DAILY` или `EMAIL_QUOTA_MONTHLY` он передает пустыми, и backend читает их как незаданные. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера. ### Доставки писем @@ -196,9 +198,22 @@ Compose передает эти переменные из корневого `.e - Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `Rebind`, что разрешено только до первой попытки. - Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован. - Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты. -- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` без `next_attempt_at` ждет сброса квоты, момент которого неизвестен, например месячной квоты Resend, и требует решения оператора. +- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора. - Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос. +### Квоты почты + +Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Шлюз квот реализован, но worker отправки, который его вызывает, запланирован (TASK-016), поэтому текущая сборка пока ничего не считает. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). + +- Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска. +- Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце. +- Когда квота исчерпана, доставки ждут в `waiting_quota` до `next_attempt_at`: ближайших 00:00 UTC для суток и первого числа следующего месяца в 00:00 UTC для месяца. Ничто не покупает тариф, не переводит аккаунт на платный план и не переносит почту на другой транспорт или аккаунт. Сам аккаунт может узнать, что его письмо ждет и до какого времени, через чтение статуса, описанное в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты); HTTP-маршрута для этого пока нет. +- Чтобы увидеть состояние, выбирайте только счетчики и метаданные, например `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'` и для отправок, которые посчитаны, но так и не рассчитаны, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. В журнале видны `mail quota is used up; the delivery waits for the reset` и, если отказал сам провайдер, `the mail provider reported its quota used up; local sending stops until the reset`. +- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит. +- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом. +- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017). +- Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита. + ### Шаблоны писем Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку; регистрация, подтверждение, сброс пароля и отправка запланированы, поэтому текущая сборка не отправляет писем. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 5ecd83e..fa84afe 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -57,7 +57,7 @@ Frontend зависимости выбираются из актуальных s - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) и таблицы доставок писем (`deliveries`, `delivery_attempts`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -197,6 +197,8 @@ Backend, запущенный напрямую с зарегистрирован Чтобы отправить уведомление из usecase, вызовите `notification.MailRequester.RequestNotification(ctx, unit, request)` с `UnitOfWork` usecase, ID аккаунта получателя и `mailtemplate.NotificationData`; вызов возвращает ID доставки. Он сохраняет текст в `mail_requests` и добавляет событие, которое несет только ID запроса и вид, оба действия - в транзакции usecase. Затем обработчик `notification_delivery` сохраняет доставку с адресом, прочитанным из аккаунта, и сформированным содержимым и удаляет запрос; аккаунты с неподтвержденным адресом он пропускает. Никогда не кладите email, токен, текст уведомления или контакт другого человека в payload любого события и никогда не кладите токен или контакт другого человека в запрос. Письма подтверждения почты и сброса пароля содержат токен и не могут идти через событие: сценарии identity создают такие доставки через `domain.NewDelivery` и `UnitOfWork.Deliveries().Create` в транзакции, которая выпускает токен. Новая версия шаблона меняет только новые доставки; никогда не обновляйте содержимое сохраненной доставки. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем), эксплуатация - в [DEPLOY.md](DEPLOY.md#доставки-писем), тесты - в [TESTING.md](TESTING.md#тесты-доставки-писем). +Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index cd28646..01213d7 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -131,7 +131,43 @@ Unit-тесты (`make -C backend test`) покрывают модель дос - Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки. - Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном. -Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы, квоты и проверка разрешений относятся к следующим задачам, и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity. +Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы и проверка разрешений относятся к следующим задачам, у квот свои [тесты квот почты](#тесты-квот-почты), и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity. + +## Тесты квот почты + +Unit-тесты (`make -C backend test`) проверяют правила квот без базы: + +- `internal/domain/`: окна суток и месяца для момента времени - календарные периоды UTC независимо от его часового пояса: полночь UTC относится к новым суткам, а наносекунда до нее - к старым, местное время после местной полуночи может еще относиться к предыдущим UTC-суткам, сброс суток 28 февраля обычного года и 29 февраля високосного приходится на 1 марта, а декабрь сбрасывается в январь следующего года; лимиты отклоняют ноль, отрицательные значения и суточный лимит больше месячного. +- `config/` и `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по умолчанию равны 100 и 3000 для `resend` и `disabled`; `smtp` без любого из них не запускается и принимает явно заданные значения; сниженное значение принимается как настроено для любого провайдера; пустое значение считается незаданным; ноль, отрицательные, нецелые значения, значения вне диапазона и суточный лимит больше месячного отклоняются без вывода секретов; bootstrap не запускается с нулевой квотой. +- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` дает `QuotaPeriod` `day` с ожиданием до полуночи, а `monthly_quota_exceeded` дает `month` без ожидания. +- `internal/usecase/notification/`, со счетчиком и журналом в памяти и поддельными часами: + - `QuotaGate.PrepareSend` допускает отправки до суточного лимита, а следующую переводит в `waiting_quota` до 00:00 UTC и не считает ее; после полуночи допускает ее. При заполненном месяце (с 31 декабря на 1 января) и при заполнении обоих окон ждет начала месяца. + - Доставку, которую последним изменил экземпляр с часами на 5 мс впереди, уже после полуночи, откладывает с этим временем изменения и без ошибки. + - Применяет сниженный лимит к `smtp` так же, как к любому транспорту; отклоняет доставку, закрепленную за аккаунтом без квоты, и ничего для нее не резервирует. + - Возвращает доставку `unknown` без изменений с моментом сброса и отклоняет конечную доставку. + - Повтор в пределах 24 часов повторно использует открытое резервирование, даже когда сутки иначе заполнены; отказ этого повтора резервирование сохраняет; после окна повтор считается заново. Шлюз `smtp`, у которого нет дедупликации провайдера, считает каждый повтор. + - `SettleSend` оставляет резервирование для `accepted` и `unknown` и возвращает его при ошибке `Send` и любом исходе `rejected`. Повторный расчет возвращает резервирование один раз. + - Ответ о суточной квоте отмечает сутки и возвращает полночь, о месячной - отмечает месяц и возвращает его конец. Ответ без окна откладывает только доставку по подсказке или без времени, а окно, которое провайдер назвал заполненным, возврат не открывает. + - Отмечается окно, текущее на момент расчета: суточный отказ 31 октября отмечает только сутки и оставляет ноябрь открытым; резервирование в 23:59:59, рассчитанное через 5 мс после полуночи, отмечает новые сутки; подсказка, вычисленная по часам провайдера на 5 мс впереди, все равно дает ровно полночь. + - `ReportQuotaUsage` пишет расход и лимиты и предупреждает о других метках аккаунта. + - `DeliveryStatusReader.LatestForUser` возвращает вид, статус и время изменения, а `WaitingUntil` только для `waiting_quota`. Он спрашивает только про указанный аккаунт, без доставки ничего не возвращает и отклоняет нулевой аккаунт и неизвестный вид. + - Журналы не содержат адреса, темы или тела. + +`TestMailQuota` в `backend/integration_test/mail_quota_test.go` использует `bootstrap(t, postgresService)`, настоящие transactor, хранилище доставок и репозиторий квот и поддельные часы. Каждый случай начинается с пустых таблиц: + +- Конкурентность: 12 отправителей, каждый со своим соединением и транзакцией, одновременно вызывают `PrepareSend`. На окнах без строк (создание строк тоже конкурирует) при суточном лимите 10 разрешение получают ровно 10; после 7 последовательных отправок из следующих 12 разрешение получают ровно 3. Каждая остальная доставка сохраняется в `waiting_quota` с `next_attempt_at` на ближайшие 00:00 UTC, а оба счетчика заканчивают на 10. Без блокировки строк случай падает: допускаются все 12. +- Полночь и граница месяца: при лимитах 2 в сутки и 3 в месяц с 30 октября 22:00 UTC третья отправка ждет до 31 октября 00:00 UTC, за секунду до этого все еще ждет, а в полночь проходит; четвертая ждет 1 ноября, потому что месяц заполнен, и тогда проходит. Строки суток и месяца содержат 2, 1, 1 и 3, 1. +- Сниженный лимит и SMTP: шлюзы собираются из `config.LoadFromEnv`. После 4 отправок через Resend с лимитом по умолчанию лимит, сниженный до 3, откладывает следующую отправку до полуночи. `smtp` без настроек квот не загружается; с 2 и 2 он допускает две отправки через relay и откладывает третью до начала месяца, а доставка Resend под шлюзом `smtp` завершается ошибкой `ErrQuotaNotConfigured` и не меняет счетчиков. +- Уточнение по провайдеру: отказ `temporary` возвращает свое резервирование. Отказ `daily_quota_exceeded` при локальном счете 1 из 100 сохраняет доставку в `waiting_quota` до полуночи с одной попыткой, поднимает строку суток до 100 с `provider_exhausted_at`, после чего шлюз сам откладывает следующую доставку. После полуночи отказ `monthly_quota_exceeded` поднимает строку месяца до 3000 и откладывает доставки до 1 ноября. +- Удаление аккаунта: три принятые отправки дают 3 из 3; удаление аккаунта каскадно удаляет его доставки и попытки, счетчики сохраняют 3, а доставка другому аккаунту в тот же день ждет до полуночи. +- Порядок блокировок, детерминированно: строка месяца лежит в heap раньше строки суток, а запись идет в сессиях с `enable_indexscan=off`, поэтому сканирование следует порядку heap, как в воспроизведенной взаимоблокировке. Третья транзакция держит строку суток; резервирование и возврат встают за ней в очередь в обоих порядках, затем блокировка снимается. Ни один не получает ошибку взаимоблокировки, а расход сходится. Если убрать упорядоченную блокировку из `Settle`, случай падает с SQLSTATE 40P01. +- Порядок блокировок, ограниченная нагрузка: 60 раундов, в каждом одновременно стартуют возврат вторых суток, возврат первых суток с отметкой вторых через полночь и два резервирования вторых суток в сессиях с порядком heap. Ни один раунд не возвращает ошибку. +- Журнал: ошибка транспорта, рассчитанная дважды, возвращается один раз. Резервирование неизвестной попытки повторно используется повтором через час и не используется после 24-часового окна. В журнале остаются 2 открытые строки, 1 возвращенная и 2 с исходом. +- Статус для пользователя: аккаунт без писем ничего не получает; после одного допущенного и одного отложенного уведомления он видит `waiting_quota` до полуночи; другой аккаунт и другой вид ничего не получают. +- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`. +- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход. + +`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016. ## Шардирование интеграционных тестов