queue.go58 lines, 1.7 KB
| 1 | package metrics |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/jackc/pgx/v5/pgxpool" |
| 9 | "github.com/prometheus/client_golang/prometheus" |
| 10 | ) |
| 11 | |
| 12 | // A Queue reads how much work is waiting, from Postgres, when Prometheus asks. |
| 13 | type Queue struct { |
| 14 | db *pgxpool.Pool |
| 15 | jobs *prometheus.Desc |
| 16 | oldest *prometheus.Desc |
| 17 | deltas *prometheus.Desc |
| 18 | } |
| 19 | |
| 20 | func NewQueue(db *pgxpool.Pool) *Queue { |
| 21 | return &Queue{ |
| 22 | db: db, |
| 23 | jobs: prometheus.NewDesc("murmur_queue_jobs", "Jobs in the queue.", []string{"status"}, nil), |
| 24 | oldest: prometheus.NewDesc("murmur_queue_oldest_seconds", "The oldest job's wait.", nil, nil), |
| 25 | deltas: prometheus.NewDesc("murmur_like_deltas", "Likes not yet in a post's count.", nil, nil), |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | func (q *Queue) Describe(ch chan<- *prometheus.Desc) { |
| 30 | ch <- q.jobs |
| 31 | ch <- q.oldest |
| 32 | ch <- q.deltas |
| 33 | } |
| 34 | |
| 35 | func (q *Queue) Collect(ch chan<- prometheus.Metric) { |
| 36 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 37 | defer cancel() |
| 38 | var waiting, running, dead, oldest, deltas float64 |
| 39 | err := q.db.QueryRow(ctx, ` |
| 40 | select count(*) filter (where status = 'waiting'), |
| 41 | count(*) filter (where status = 'running'), |
| 42 | count(*) filter (where status = 'dead'), |
| 43 | coalesce(extract(epoch from now() - min(created_at) filter (where status <> 'dead')), 0), |
| 44 | (select count(*) from like_deltas) |
| 45 | from jobs`).Scan(&waiting, &running, &dead, &oldest, &deltas) |
| 46 | if err != nil { |
| 47 | slog.Error("the queue was not measured", "error", err) |
| 48 | return |
| 49 | } |
| 50 | gauge := func(d *prometheus.Desc, v float64, labels ...string) { |
| 51 | ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, labels...) |
| 52 | } |
| 53 | gauge(q.jobs, waiting, "waiting") |
| 54 | gauge(q.jobs, running, "running") |
| 55 | gauge(q.jobs, dead, "dead") |
| 56 | gauge(q.oldest, oldest) |
| 57 | gauge(q.deltas, deltas) |
| 58 | } |