feat(notification): add Resend quota gate and waiting-for-reset state

This commit is contained in:
shira committed 2026-10-06 11:50:38 +03:00
1 parent 3b917befa9
commit b856d4ff54
40 files changed
+4116 -48

No files matched your search

@@ -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;
+18
View File
@@ -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;
+193
View File
@@ -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;