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

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

No files matched your search

@@ -0,0 +1,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())
}
}
}