feat(observability): add product metrics for API, outbox and delivery

This commit is contained in:
shira committed 2026-10-06 19:48:15 +03:00
1 parent 560724e2aa
commit 94488e2b57
51 files changed
+3655 -68

No files matched your search

+21 -12
View File
@@ -18,6 +18,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/deliverymetrics"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/outboxrelay"
)
@@ -45,6 +46,9 @@ type Application struct {
// is nil when the worker is disabled, no job kind is registered, or the
// database is not configured.
jobs *jobrunner.Worker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
}
func NewApplication(
@@ -56,16 +60,18 @@ func NewApplication(
relay *outboxrelay.Relay,
consumers eventConsumers,
jobs *jobrunner.Worker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
deliveryMetrics: deliveryMetrics,
}
}
@@ -191,10 +197,10 @@ func (application *Application) run(ctx context.Context) error {
return err
}
// startWorkers runs the relay, every consumer, and the scheduled job worker
// until ctx ends and returns a channel that closes when all of them have
// stopped. The workers stop together with the servers; none of them
// depends on another.
// startWorkers runs the relay, every consumer, the scheduled job worker, and
// the delivery metrics sampler until ctx ends and returns a channel that
// closes when all of them have stopped. The workers stop together with the
// servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
@@ -206,6 +212,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.jobs != nil {
workers.Go(func() { application.jobs.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
+1 -1
View File
@@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -0,0 +1,80 @@
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
}
@@ -0,0 +1,81 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
func TestNewDeliveryMetricsSkipsWithoutADatabase(t *testing.T) {
sampler, cleanup, err := newDeliveryMetrics(t.Context(), config.Config{EmailProvider: config.EmailProviderDisabled},
slog.New(slog.DiscardHandler), prometheus.New())
if err != nil {
t.Fatalf("newDeliveryMetrics() error = %v", err)
}
cleanup()
if sampler != nil {
t.Fatal("newDeliveryMetrics() built a sampler without DATABASE_URL")
}
}
func TestDeliveryMetricsQuotaFollowsTheTransport(t *testing.T) {
quota, err := deliveryMetricsQuota(config.Config{EmailProvider: config.EmailProviderDisabled})
if err != nil || quota != nil {
t.Fatalf("deliveryMetricsQuota(disabled) = %v, %v; want no quota", quota, err)
}
quota, err = deliveryMetricsQuota(config.Config{
EmailProvider: config.EmailProviderResend,
EmailAccount: "primary",
EmailQuotaDaily: 100,
EmailQuotaMonthly: 3000,
})
if err != nil {
t.Fatalf("deliveryMetricsQuota(resend) error = %v", err)
}
if quota.Account.Provider() != "resend" || quota.Account.Account() != "primary" || quota.Limits.Daily() != 100 || quota.Limits.Monthly() != 3000 {
t.Fatalf("deliveryMetricsQuota(resend) = %+v", quota)
}
if _, err := deliveryMetricsQuota(config.Config{EmailProvider: config.EmailProviderSMTP, EmailAccount: "Not A Label", EmailQuotaDaily: 1, EmailQuotaMonthly: 1}); err == nil {
t.Fatal("deliveryMetricsQuota() accepted an invalid account label")
}
}
// TestApplicationRunsAndStopsTheDeliveryMetricsSampler starts the sampler
// against a database that does not answer: it logs stale gauges, and the
// application still stops within its shutdown budget.
func TestApplicationRunsAndStopsTheDeliveryMetricsSampler(t *testing.T) {
settings := consumerTestConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
sampler, cleanup, err := newDeliveryMetrics(t.Context(), settings, logger, metrics)
if err != nil {
t.Fatalf("newDeliveryMetrics() error = %v", err)
}
defer cleanup()
if sampler == nil {
t.Fatal("newDeliveryMetrics() built no sampler with DATABASE_URL set")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
time.Sleep(50 * time.Millisecond)
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
}
+1 -1
View File
@@ -87,7 +87,7 @@ func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -50,6 +50,7 @@ func initialize(
newOutboxRelay,
newEventConsumers,
newJobWorker,
newDeliveryMetrics,
NewApplication,
),
)
+12 -1
View File
@@ -79,8 +79,19 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker)
sampler, cleanup7, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, sampler)
return application, func() {
cleanup7()
cleanup6()
cleanup5()
cleanup4()