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 }