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

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