Files
lincodex/backend/internal/adapter/secondary/prometheus/metrics.go
T

259 lines
10 KiB
Go

package prometheus
import (
"net/http"
"strconv"
"time"
client "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"lincodex/backend/internal/port/outbound"
)
type Metrics struct {
registry *client.Registry
requests *client.CounterVec
// latency carries the status class, so a fast stream of rejected
// requests does not hide slow successful ones.
latency *client.HistogramVec
// problems counts error responses by the problem code they carry.
problems *client.CounterVec
// relayEvents counts outbox events by relay outcome: published or
// failed. A failed event stays pending and is counted again on every
// retry.
relayEvents *client.CounterVec
// relayPending and relayOldestAge describe the unpublished outbox
// events. Every backend instance reports the same database-wide values,
// so dashboards aggregate them with max, not sum.
relayPending client.Gauge
relayOldestAge client.Gauge
// consumerRecords counts consumed records by consumer and final
// outcome; every record ends with exactly one outcome.
consumerRecords *client.CounterVec
// consumerFailures counts every failed consumer operation, including the
// last handler attempt before a dead letter, by the stage that failed.
consumerFailures *client.CounterVec
// scheduledJobs counts claimed scheduled jobs by kind and outcome:
// done, retry, dead, lease_lost, or released.
scheduledJobs *client.CounterVec
// scheduledJobsDue, scheduledJobsOldestDueAge, and scheduledJobsDead
// describe the waiting and dead jobs. Every backend instance reports the
// same database-wide values, so dashboards aggregate them with max.
scheduledJobsDue client.Gauge
scheduledJobsOldestDueAge client.Gauge
scheduledJobsDead client.Gauge
mail mailMetrics
assessment assessmentMetrics
}
// Outbox relay outcome label values.
const (
relayOutcomePublished = "published"
relayOutcomeFailed = "failed"
)
// Event consumer label values. They mirror the eventconsumer constants, which
// this adapter does not import; PrepareEventConsumer creates these series.
var (
consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"}
consumerStages = []string{"handler", "store", "poll", "commit"}
// scheduledJobOutcomes mirror the jobrunner outcome constants.
scheduledJobOutcomes = []string{"done", "retry", "dead", "lease_lost", "released"}
)
func New() *Metrics {
registry := client.NewRegistry()
requests := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_http_requests_total",
Help: "Total number of HTTP requests served by the API.",
}, []string{"method", "route", "status"})
latency := client.NewHistogramVec(client.HistogramOpts{
Name: "lincodex_http_request_duration_seconds",
Help: "HTTP request duration in seconds, by method, route template, and status class.",
Buckets: client.DefBuckets,
}, []string{"method", "route", "status_class"})
problems := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_http_problems_total",
Help: "Public API error responses by route template and the code of the RFC 9457 problem they carry.",
}, []string{"route", "code"})
relayEvents := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_outbox_relay_events_total",
Help: "Outbox events handled by the relay, by outcome; failed events stay pending and are retried.",
}, []string{"outcome"})
relayPending := client.NewGauge(client.GaugeOpts{
Name: "lincodex_outbox_relay_pending_events",
Help: "Unpublished outbox events at the last backlog read by the relay.",
})
relayOldestAge := client.NewGauge(client.GaugeOpts{
Name: "lincodex_outbox_relay_oldest_pending_age_seconds",
Help: "Age of the earliest unpublished outbox event at the last backlog read by the relay; 0 without pending events.",
})
consumerRecords := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_event_consumer_records_total",
Help: "Event bus records finished by a consumer, by outcome: applied, duplicate, ignored, or dead_lettered.",
}, []string{"consumer", "outcome"})
consumerFailures := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_event_consumer_failures_total",
Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.",
}, []string{"consumer", "stage"})
scheduledJobs := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_scheduled_jobs_total",
Help: "Claimed scheduled jobs by kind and outcome: done, retry, dead, lease_lost, or released.",
}, []string{"kind", "outcome"})
scheduledJobsDue := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_due",
Help: "Scheduled jobs that fell due and wait for a worker, at the last backlog read.",
})
scheduledJobsOldestDueAge := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_oldest_due_age_seconds",
Help: "How long the earliest waiting scheduled job has been due, by the application clock, at the last backlog read; 0 without due jobs.",
})
scheduledJobsDead := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_dead",
Help: "Dead scheduled jobs, which need an operator, at the last backlog read.",
})
mail := newMailMetrics()
assessment := newAssessmentMetrics()
registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
requests, latency, problems, relayEvents, relayPending, relayOldestAge,
consumerRecords, consumerFailures,
scheduledJobs, scheduledJobsDue, scheduledJobsOldestDueAge, scheduledJobsDead,
)
registry.MustRegister(mail.collectors()...)
registry.MustRegister(assessment.collectors()...)
// Expose both series from the start so rate queries see zero, not absence.
relayEvents.WithLabelValues(relayOutcomePublished)
relayEvents.WithLabelValues(relayOutcomeFailed)
return &Metrics{
registry: registry,
requests: requests,
latency: latency,
problems: problems,
relayEvents: relayEvents,
relayPending: relayPending,
relayOldestAge: relayOldestAge,
consumerRecords: consumerRecords,
consumerFailures: consumerFailures,
scheduledJobs: scheduledJobs,
scheduledJobsDue: scheduledJobsDue,
scheduledJobsOldestDueAge: scheduledJobsOldestDueAge,
scheduledJobsDead: scheduledJobsDead,
mail: mail,
assessment: assessment,
}
}
// PrepareScheduledJobKind exposes every outcome series of kind at zero, so
// an alert on the first dead job sees an increase instead of a new series.
func (metrics *Metrics) PrepareScheduledJobKind(kind string) {
for _, outcome := range scheduledJobOutcomes {
metrics.scheduledJobs.WithLabelValues(kind, outcome)
}
}
// ObserveScheduledJob counts the outcome of one claimed job.
func (metrics *Metrics) ObserveScheduledJob(kind, outcome string) {
metrics.scheduledJobs.WithLabelValues(kind, outcome).Inc()
}
// ObserveScheduledJobBacklog records the latest backlog read.
func (metrics *Metrics) ObserveScheduledJobBacklog(backlog outbound.JobBacklog) {
metrics.scheduledJobsDue.Set(float64(backlog.Due))
metrics.scheduledJobsOldestDueAge.Set(backlog.OldestDueAge.Seconds())
metrics.scheduledJobsDead.Set(float64(backlog.Dead))
}
// PrepareEventConsumer exposes every series of consumer at zero, so an alert
// on the first dead letter sees an increase instead of a new series.
func (metrics *Metrics) PrepareEventConsumer(consumer string) {
for _, outcome := range consumerOutcomes {
metrics.consumerRecords.WithLabelValues(consumer, outcome)
}
for _, stage := range consumerStages {
metrics.consumerFailures.WithLabelValues(consumer, stage)
}
}
// ObserveConsumedRecord counts one finished record.
func (metrics *Metrics) ObserveConsumedRecord(consumer, outcome string) {
metrics.consumerRecords.WithLabelValues(consumer, outcome).Inc()
}
// ObserveConsumerFailure counts one failed handler attempt, store
// operation, poll, or offset commit.
func (metrics *Metrics) ObserveConsumerFailure(consumer, stage string) {
metrics.consumerFailures.WithLabelValues(consumer, stage).Inc()
}
// ObserveOutboxBacklog records the latest backlog read.
func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
metrics.relayPending.Set(float64(backlog.Pending))
metrics.relayOldestAge.Set(backlog.OldestAge.Seconds())
}
// ObserveOutboxRelayPass adds the events one relay pass published and those
// it claimed but could not publish.
func (metrics *Metrics) ObserveOutboxRelayPass(published, failed int) {
if published > 0 {
metrics.relayEvents.WithLabelValues(relayOutcomePublished).Add(float64(published))
}
if failed > 0 {
metrics.relayEvents.WithLabelValues(relayOutcomeFailed).Add(float64(failed))
}
}
func (metrics *Metrics) ObserveRequest(method, route string, status int, duration time.Duration) {
if route == "" {
route = "unmatched"
}
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
default:
method = "OTHER"
}
metrics.requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
metrics.latency.WithLabelValues(method, route, statusClass(status)).Observe(duration.Seconds())
}
// problemCodes mirror the problem codes of the public contract, which this
// adapter does not import; a test in the HTTP adapter checks that every
// contract code is listed.
var problemCodes = []string{
"validation_failed", "verification_token_invalid", "verification_token_expired",
"unauthenticated", "invalid_credentials", "forbidden", "email_not_verified",
"csrf_check_failed", "not_found", "method_not_allowed", "idempotency_in_progress",
"state_conflict", "version_conflict", "payload_too_large", "unsupported_media_type",
"idempotency_key_reused", "precondition_required", "rate_limited", "internal",
"not_implemented",
"service_unavailable",
}
// ObserveProblem counts one error response. A code outside the contract
// catalogue is counted as "other"; an empty route is the unmatched one.
func (metrics *Metrics) ObserveProblem(route, code string) {
if route == "" {
route = "unmatched"
}
metrics.problems.WithLabelValues(route, boundedLabel(code, problemCodes)).Inc()
}
// statusClass maps a status code to 1xx-5xx, or "other" outside them.
func statusClass(status int) string {
if status < 100 || status > 599 {
return "other"
}
return strconv.Itoa(status/100) + "xx"
}
func (metrics *Metrics) Handler() http.Handler {
return promhttp.HandlerFor(metrics.registry, promhttp.HandlerOpts{})
}