209 lines
6.9 KiB
Go
209 lines
6.9 KiB
Go
package deliverymetrics
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/pkg/testutil"
|
|
)
|
|
|
|
const testInterval = time.Second
|
|
|
|
var errDatabaseDown = errors.New("database down")
|
|
|
|
type fakeStatistics struct {
|
|
statistics outbound.DeliveryStatistics
|
|
err error
|
|
}
|
|
|
|
func (reader fakeStatistics) DeliveryStatistics(context.Context) (outbound.DeliveryStatistics, error) {
|
|
return reader.statistics, reader.err
|
|
}
|
|
|
|
type fakeUsage struct {
|
|
usage outbound.MailQuotaUsage
|
|
err error
|
|
windows domain.MailQuotaWindows
|
|
}
|
|
|
|
func (reader *fakeUsage) Usage(_ context.Context, _ domain.MailProviderAccount, windows domain.MailQuotaWindows) (outbound.MailQuotaUsage, error) {
|
|
reader.windows = windows
|
|
return reader.usage, reader.err
|
|
}
|
|
|
|
func (*fakeUsage) OtherAccountsWithUsage(context.Context, domain.MailProviderAccount, time.Time) ([]string, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
type recordingMetrics struct {
|
|
mu sync.Mutex
|
|
states int
|
|
counts []outbound.DeliveryStatusCount
|
|
oldest time.Duration
|
|
quotas int
|
|
provider string
|
|
usage outbound.MailQuotaUsage
|
|
dailyLimit int64
|
|
prepared int
|
|
successes []time.Time
|
|
}
|
|
|
|
func (metrics *recordingMetrics) PrepareMailMetricsReads() {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
metrics.prepared++
|
|
}
|
|
|
|
func (metrics *recordingMetrics) ObserveMailMetricsReadSuccess(at time.Time) {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
metrics.successes = append(metrics.successes, at)
|
|
}
|
|
|
|
func (metrics *recordingMetrics) preparations() int {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
return metrics.prepared
|
|
}
|
|
|
|
func (metrics *recordingMetrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldest time.Duration) {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
metrics.states++
|
|
metrics.counts, metrics.oldest = counts, oldest
|
|
}
|
|
|
|
func (metrics *recordingMetrics) ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits) {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
metrics.quotas++
|
|
metrics.provider, metrics.usage, metrics.dailyLimit = provider, usage, limits.Daily()
|
|
}
|
|
|
|
func (metrics *recordingMetrics) samples() int {
|
|
metrics.mu.Lock()
|
|
defer metrics.mu.Unlock()
|
|
return metrics.states
|
|
}
|
|
|
|
func testQuota(t *testing.T, reader outbound.MailQuotaUsageReader) *Quota {
|
|
t.Helper()
|
|
account, err := domain.NewMailProviderAccount("resend", "default")
|
|
if err != nil {
|
|
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
|
}
|
|
limits, err := domain.NewMailQuotaLimits(100, 3000)
|
|
if err != nil {
|
|
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
|
}
|
|
return &Quota{Reader: reader, Account: account, Limits: limits}
|
|
}
|
|
|
|
func TestSampleReportsStatesTheOldestDuePendingAgeAndTheQuota(t *testing.T) {
|
|
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
|
counts := []outbound.DeliveryStatusCount{
|
|
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 2},
|
|
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusAccepted, Deliveries: 5},
|
|
}
|
|
usage := &fakeUsage{usage: outbound.MailQuotaUsage{DayUsed: 7, MonthUsed: 40}}
|
|
metrics := &recordingMetrics{}
|
|
sampler := New(
|
|
fakeStatistics{statistics: outbound.DeliveryStatistics{Counts: counts, EarliestPendingAttemptAt: now.Add(-90 * time.Second)}},
|
|
testQuota(t, usage), metrics, slog.New(slog.DiscardHandler), testInterval, testutil.NewFakeClock(now).Now,
|
|
)
|
|
if err := sampler.Sample(t.Context()); err != nil {
|
|
t.Fatalf("Sample() error = %v", err)
|
|
}
|
|
if len(metrics.counts) != len(counts) || metrics.oldest != 90*time.Second {
|
|
t.Fatalf("observed %v and %s, want %v and 90s", metrics.counts, metrics.oldest, counts)
|
|
}
|
|
if metrics.provider != "resend" || metrics.usage != usage.usage || metrics.dailyLimit != 100 {
|
|
t.Fatalf("observed quota %q %+v %d", metrics.provider, metrics.usage, metrics.dailyLimit)
|
|
}
|
|
if want := domain.MailQuotaWindowsAt(now); usage.windows != want {
|
|
t.Fatalf("read windows %+v, want the current %+v", usage.windows, want)
|
|
}
|
|
if len(metrics.successes) != 1 || !metrics.successes[0].Equal(now) {
|
|
t.Fatalf("recorded successes %v, want one at %s", metrics.successes, now)
|
|
}
|
|
}
|
|
|
|
func TestSampleTreatsAPendingDeliveryThatIsNotDueAsNotLate(t *testing.T) {
|
|
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
|
metrics := &recordingMetrics{oldest: time.Hour}
|
|
sampler := New(
|
|
fakeStatistics{statistics: outbound.DeliveryStatistics{EarliestPendingAttemptAt: now.Add(time.Minute)}},
|
|
nil, metrics, slog.New(slog.DiscardHandler), testInterval, testutil.NewFakeClock(now).Now,
|
|
)
|
|
if err := sampler.Sample(t.Context()); err != nil {
|
|
t.Fatalf("Sample() error = %v", err)
|
|
}
|
|
if metrics.oldest != 0 || metrics.quotas != 0 {
|
|
t.Fatalf("observed age %s and %d quota reads, want 0 and none without a transport", metrics.oldest, metrics.quotas)
|
|
}
|
|
}
|
|
|
|
// One failed read leaves its gauges stale but does not skip the other.
|
|
func TestSampleReadsTheQuotaWhenTheDeliveryReadFails(t *testing.T) {
|
|
metrics := &recordingMetrics{}
|
|
sampler := New(
|
|
fakeStatistics{err: errDatabaseDown}, testQuota(t, &fakeUsage{}), metrics,
|
|
slog.New(slog.DiscardHandler), testInterval, time.Now,
|
|
)
|
|
err := sampler.Sample(t.Context())
|
|
if !errors.Is(err, errDatabaseDown) {
|
|
t.Fatalf("Sample() error = %v, want the read failure", err)
|
|
}
|
|
if metrics.states != 0 || metrics.quotas != 1 || len(metrics.successes) != 0 {
|
|
t.Fatalf("observed %d state and %d quota samples and %d successes, want 0, 1, and none", metrics.states, metrics.quotas, len(metrics.successes))
|
|
}
|
|
|
|
metrics = &recordingMetrics{}
|
|
sampler = New(
|
|
fakeStatistics{}, testQuota(t, &fakeUsage{err: errDatabaseDown}), metrics,
|
|
slog.New(slog.DiscardHandler), testInterval, time.Now,
|
|
)
|
|
if err := sampler.Sample(t.Context()); !errors.Is(err, errDatabaseDown) {
|
|
t.Fatalf("Sample() error = %v, want the read failure", err)
|
|
}
|
|
if metrics.states != 1 || metrics.quotas != 0 || len(metrics.successes) != 0 {
|
|
t.Fatalf("observed %d state and %d quota samples and %d successes, want 1, 0, and none", metrics.states, metrics.quotas, len(metrics.successes))
|
|
}
|
|
}
|
|
|
|
func TestRunSamplesAtOnceAndStopsWithItsContext(t *testing.T) {
|
|
metrics := &recordingMetrics{}
|
|
sampler := New(fakeStatistics{}, nil, metrics, slog.New(slog.DiscardHandler), time.Hour, time.Now)
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
defer close(stopped)
|
|
sampler.Run(ctx)
|
|
}()
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for metrics.samples() == 0 {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("Run() did not sample at start")
|
|
}
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
cancel()
|
|
select {
|
|
case <-stopped:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("Run() did not stop after cancellation")
|
|
}
|
|
if samples := metrics.samples(); samples != 1 {
|
|
t.Fatalf("Run() sampled %d times within one interval, want 1", samples)
|
|
}
|
|
if prepared := metrics.preparations(); prepared != 1 {
|
|
t.Fatalf("Run() prepared the last success time %d times, want once", prepared)
|
|
}
|
|
}
|