metrics.go37 lines, 1.2 KB
| 1 | package outbox |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "math" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/jackc/pgx/v5/pgxpool" |
| 9 | "github.com/prometheus/client_golang/prometheus" |
| 10 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 11 | ) |
| 12 | |
| 13 | // RegisterMetrics reports the outbox's backlog to Prometheus, fresh at every |
| 14 | // scrape: how many events wait to be published, and how long the oldest has |
| 15 | // waited. A growing lag means the relay is stuck, or NATS is down. |
| 16 | func RegisterMetrics(pool *pgxpool.Pool) { |
| 17 | query := func(sql string) func() float64 { |
| 18 | return func() float64 { |
| 19 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 20 | defer cancel() |
| 21 | var v float64 |
| 22 | if err := pool.QueryRow(ctx, sql).Scan(&v); err != nil { |
| 23 | return math.NaN() // unknown, which isn't zero |
| 24 | } |
| 25 | return v |
| 26 | } |
| 27 | } |
| 28 | promauto.NewGaugeFunc(prometheus.GaugeOpts{ |
| 29 | Name: "outbox_pending_events", |
| 30 | Help: "Events written to the outbox, and not published yet.", |
| 31 | }, query(`SELECT count(*) FROM outbox WHERE published_at IS NULL`)) |
| 32 | promauto.NewGaugeFunc(prometheus.GaugeOpts{ |
| 33 | Name: "outbox_lag_seconds", |
| 34 | Help: "How long the oldest unpublished event has waited.", |
| 35 | }, query(`SELECT coalesce(extract(epoch FROM now() - min(created_at)), 0) |
| 36 | FROM outbox WHERE published_at IS NULL`)) |
| 37 | } |