package bootstrap import ( "context" "fmt" "log/slog" "time" "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/worker/deliverymetrics" ) const ( // deliveryMetricsPoolMaxConns covers the reads of one sample, which run // one after another. deliveryMetricsPoolMaxConns = 1 // deliveryMetricsInterval matches the usual Prometheus scrape interval. // The delivery read scans the deliveries table, so it is not repeated // more often than a scrape can show it. deliveryMetricsInterval = 30 * time.Second ) var _ deliverymetrics.Metrics = (*prometheus.Metrics)(nil) // newDeliveryMetrics builds the delivery metrics sampler and the PostgreSQL // pool it owns. Nothing connects here; an unavailable database leaves the // gauges stale and logs a warning per sample. It returns no sampler when // DATABASE_URL is unset. The quota part runs only for an active transport. func newDeliveryMetrics( ctx context.Context, settings config.Config, logger *slog.Logger, metrics *prometheus.Metrics, ) (*deliverymetrics.Sampler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("delivery metrics sampler skipped because DATABASE_URL is not set") return nil, func() {}, nil } quota, err := deliveryMetricsQuota(settings) if err != nil { return nil, nil, err } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, deliveryMetricsPoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newDeliveryMetrics - create pool: %w", err) } if quota != nil { quota.Reader = postgres.NewMailQuotaStore(pool).MailQuotas() } sampler := deliverymetrics.New( postgres.NewDeliveryStatisticsStore(pool), quota, metrics, logger.With(slog.String("component", "delivery_metrics")), deliveryMetricsInterval, time.Now, ) // The application stops the sampler before this cleanup runs. return sampler, pool.Close, nil } // deliveryMetricsQuota returns the configured account and limits without a // reader, or nil for EMAIL_PROVIDER=disabled, which has no quota. func deliveryMetricsQuota(settings config.Config) (*deliverymetrics.Quota, error) { if settings.EmailProvider == config.EmailProviderDisabled { return nil, nil } account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount) if err != nil { return nil, fmt.Errorf("bootstrap.deliveryMetricsQuota - provider account: %w", err) } limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly)) if err != nil { return nil, fmt.Errorf("bootstrap.deliveryMetricsQuota - limits: %w", err) } return &deliverymetrics.Quota{Account: account, Limits: limits}, nil }