feat(observability): add product metrics for API, outbox and delivery
This commit is contained in:
1 parent
560724e2aa
commit
94488e2b57
51 files changed
+3655
-68
No files matched your search
@@ -0,0 +1,117 @@
|
||||
// Package deliverymetrics periodically reads the delivery and mail quota
|
||||
// aggregates from the database into the metrics. The database stores no
|
||||
// metrics, so the gauges come from cheap periodic reads instead of a query
|
||||
// per scrape.
|
||||
package deliverymetrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
)
|
||||
|
||||
// Metrics records the aggregates without per-delivery or per-account labels.
|
||||
type Metrics interface {
|
||||
ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldestDuePending time.Duration)
|
||||
ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits)
|
||||
PrepareMailMetricsReads()
|
||||
ObserveMailMetricsReadSuccess(at time.Time)
|
||||
}
|
||||
|
||||
// Quota names the configured provider account whose current windows the
|
||||
// sampler reports, with its configured limits.
|
||||
type Quota struct {
|
||||
Reader outbound.MailQuotaUsageReader
|
||||
Account domain.MailProviderAccount
|
||||
Limits domain.MailQuotaLimits
|
||||
}
|
||||
|
||||
// Sampler reads the aggregates once per interval. Every backend instance
|
||||
// reports the same database-wide values.
|
||||
type Sampler struct {
|
||||
deliveries outbound.DeliveryStatisticsReader
|
||||
// quota is nil when no transport is configured, for example with
|
||||
// EMAIL_PROVIDER=disabled.
|
||||
quota *Quota
|
||||
metrics Metrics
|
||||
logger *slog.Logger
|
||||
interval time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// New builds a sampler. interval is the time between two reads and also
|
||||
// bounds one read; now is the application clock that wrote the delivery
|
||||
// times.
|
||||
func New(
|
||||
deliveries outbound.DeliveryStatisticsReader,
|
||||
quota *Quota,
|
||||
metrics Metrics,
|
||||
logger *slog.Logger,
|
||||
interval time.Duration,
|
||||
now func() time.Time,
|
||||
) *Sampler {
|
||||
return &Sampler{deliveries: deliveries, quota: quota, metrics: metrics, logger: logger, interval: interval, now: now}
|
||||
}
|
||||
|
||||
// Run samples at once and then every interval until ctx ends. A failed read
|
||||
// is logged and the gauges keep their previous values until the next read
|
||||
// succeeds.
|
||||
func (sampler *Sampler) Run(ctx context.Context) {
|
||||
sampler.metrics.PrepareMailMetricsReads()
|
||||
sampler.logger.Info("delivery metrics sampler started", slog.Duration("interval", sampler.interval))
|
||||
defer sampler.logger.Info("delivery metrics sampler stopped")
|
||||
for {
|
||||
if err := sampler.Sample(ctx); err != nil && ctx.Err() == nil {
|
||||
sampler.logger.Warn("delivery metrics could not be read; the gauges are stale", slog.Any("error", err))
|
||||
}
|
||||
if !retry.Wait(ctx, sampler.interval) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sample reads both aggregates once. A failure of one read does not skip the
|
||||
// other; only a sample in which every read succeeded advances the last
|
||||
// success time.
|
||||
func (sampler *Sampler) Sample(ctx context.Context) error {
|
||||
readCtx, cancel := context.WithTimeout(ctx, sampler.interval)
|
||||
defer cancel()
|
||||
if err := errors.Join(sampler.sampleDeliveries(readCtx), sampler.sampleQuota(readCtx)); err != nil {
|
||||
return err
|
||||
}
|
||||
sampler.metrics.ObserveMailMetricsReadSuccess(sampler.now())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sampler *Sampler) sampleDeliveries(ctx context.Context) error {
|
||||
statistics, err := sampler.deliveries.DeliveryStatistics(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Sampler.sampleDeliveries - read delivery statistics: %w", err)
|
||||
}
|
||||
var oldestDuePending time.Duration
|
||||
if !statistics.EarliestPendingAttemptAt.IsZero() {
|
||||
// A pending delivery that is not due yet is not late.
|
||||
oldestDuePending = max(sampler.now().Sub(statistics.EarliestPendingAttemptAt), 0)
|
||||
}
|
||||
sampler.metrics.ObserveDeliveryStates(statistics.Counts, oldestDuePending)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sampler *Sampler) sampleQuota(ctx context.Context) error {
|
||||
if sampler.quota == nil {
|
||||
return nil
|
||||
}
|
||||
windows := domain.MailQuotaWindowsAt(sampler.now())
|
||||
usage, err := sampler.quota.Reader.Usage(ctx, sampler.quota.Account, windows)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Sampler.sampleQuota - read quota usage: %w", err)
|
||||
}
|
||||
sampler.metrics.ObserveMailQuota(sampler.quota.Account.Provider(), usage, sampler.quota.Limits)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user