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