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

@@ -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.