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