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

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