feat(notification): add Resend quota gate and waiting-for-reset state
This commit is contained in:
1 parent
3b917befa9
commit
b856d4ff54
40 files changed
+4116
-48
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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 "<period_kind>/<YYYY-MM-DD>". 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;
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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...)
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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 "<period_kind>/<YYYY-MM-DD>". 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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 "<period_kind>/<YYYY-MM-DD>". 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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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{}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -52,6 +52,7 @@ type UnitOfWork interface {
|
||||
Policies() PolicyRepository
|
||||
Deliveries() DeliveryRepository
|
||||
MailRequests() MailRequestRepository
|
||||
MailQuotas() MailQuotaRepository
|
||||
Outbox() OutboxWriter
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
// <WaitingUntil>"; 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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user