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

@@ -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.
+3 -2
View File
@@ -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)
+53
View File
@@ -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)
}
}
+4
View File
@@ -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) {
+112
View File
@@ -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{}
}
}
+120
View File
@@ -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.
+8
View File
@@ -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] = &quotaWindowState{}
}
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 := &quotaHarness{
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())
}
}
}