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] = "aWindowState{} } 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 := "aHarness{ 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()) } } }