feat(observability): add product metrics for API, outbox and delivery
This commit is contained in:
1 parent
560724e2aa
commit
94488e2b57
51 files changed
+3655
-68
No files matched your search
@@ -0,0 +1,59 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// DeliveryStatisticsStore reads the delivery aggregate behind the metrics on
|
||||
// a pool connection, with GetDeliveryStatistics.
|
||||
type DeliveryStatisticsStore struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewDeliveryStatisticsStore(pool *pgxpool.Pool) *DeliveryStatisticsStore {
|
||||
return &DeliveryStatisticsStore{queries: sqlc.New(standaloneDB{pool: pool})}
|
||||
}
|
||||
|
||||
var _ outbound.DeliveryStatisticsReader = (*DeliveryStatisticsStore)(nil)
|
||||
|
||||
func (store *DeliveryStatisticsStore) DeliveryStatistics(ctx context.Context) (outbound.DeliveryStatistics, error) {
|
||||
rows, err := store.queries.GetDeliveryStatistics(ctx)
|
||||
if err != nil {
|
||||
return outbound.DeliveryStatistics{}, fmt.Errorf("DeliveryStatisticsStore.DeliveryStatistics - read: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
statistics := outbound.DeliveryStatistics{Counts: make([]outbound.DeliveryStatusCount, 0, len(rows))}
|
||||
for _, row := range rows {
|
||||
count, err := deliveryStatusCount(row.Kind, row.Status, row.Deliveries)
|
||||
if err != nil {
|
||||
return outbound.DeliveryStatistics{}, fmt.Errorf("DeliveryStatisticsStore.DeliveryStatistics - read row: %w", err)
|
||||
}
|
||||
statistics.Counts = append(statistics.Counts, count)
|
||||
earliest := row.EarliestPendingAttemptAt
|
||||
if earliest.Valid && (statistics.EarliestPendingAttemptAt.IsZero() || earliest.Time.Before(statistics.EarliestPendingAttemptAt)) {
|
||||
statistics.EarliestPendingAttemptAt = earliest.Time
|
||||
}
|
||||
}
|
||||
return statistics, nil
|
||||
}
|
||||
|
||||
// deliveryStatusCount parses the stored kind and status, which the table
|
||||
// constraints already restrict, so a metric label never carries a value
|
||||
// outside the domain sets.
|
||||
func deliveryStatusCount(kind, status string, deliveries int64) (outbound.DeliveryStatusCount, error) {
|
||||
parsedKind, err := domain.ParseMailKind(kind)
|
||||
if err != nil {
|
||||
return outbound.DeliveryStatusCount{}, fmt.Errorf("postgres.deliveryStatusCount - parse kind: %w", err)
|
||||
}
|
||||
parsedStatus, err := domain.ParseDeliveryStatus(status)
|
||||
if err != nil {
|
||||
return outbound.DeliveryStatusCount{}, fmt.Errorf("postgres.deliveryStatusCount - parse status: %w", err)
|
||||
}
|
||||
return outbound.DeliveryStatusCount{Kind: parsedKind, Status: parsedStatus, Deliveries: deliveries}, nil
|
||||
}
|
||||
@@ -80,6 +80,55 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many
|
||||
SELECT
|
||||
kind,
|
||||
status,
|
||||
count(*) AS deliveries,
|
||||
min(next_attempt_at) FILTER (
|
||||
WHERE status = 'pending'
|
||||
)::timestamptz AS earliest_pending_attempt_at
|
||||
FROM deliveries
|
||||
GROUP BY kind, status
|
||||
`
|
||||
|
||||
type GetDeliveryStatisticsRow struct {
|
||||
Kind string
|
||||
Status string
|
||||
Deliveries int64
|
||||
EarliestPendingAttemptAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Aggregates the deliveries by kind and status for the metrics, at most once
|
||||
// per metrics interval. It reads only kind, status, and next_attempt_at,
|
||||
// never an address, a body, or an ID. No index covers status, so it scans
|
||||
// the table; add an index on (status) or keep per-status counters before
|
||||
// the table holds millions of rows.
|
||||
func (q *Queries) GetDeliveryStatistics(ctx context.Context) ([]GetDeliveryStatisticsRow, error) {
|
||||
rows, err := q.db.Query(ctx, getDeliveryStatistics)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []GetDeliveryStatisticsRow
|
||||
for rows.Next() {
|
||||
var i GetDeliveryStatisticsRow
|
||||
if err := rows.Scan(
|
||||
&i.Kind,
|
||||
&i.Status,
|
||||
&i.Deliveries,
|
||||
&i.EarliestPendingAttemptAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const getLatestDeliveryStatus = `-- name: GetLatestDeliveryStatus :one
|
||||
SELECT
|
||||
id,
|
||||
|
||||
@@ -99,6 +99,12 @@ type Querier interface {
|
||||
// after it.
|
||||
GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
|
||||
// Aggregates the deliveries by kind and status for the metrics, at most once
|
||||
// per metrics interval. It reads only kind, status, and next_attempt_at,
|
||||
// never an address, a body, or an ID. No index covers status, so it scans
|
||||
// the table; add an index on (status) or keep per-status counters before
|
||||
// the table holds millions of rows.
|
||||
GetDeliveryStatistics(ctx context.Context) ([]GetDeliveryStatisticsRow, error)
|
||||
// Among the versions of a family already effective at a time, the newest
|
||||
// publication wins. A version scheduled for later therefore never undoes a
|
||||
// version published after it. The unique (policy_key, version) index serves
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
client "github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// otherLabelValue replaces a label value outside its closed set, so a caller
|
||||
// mistake cannot create unbounded series.
|
||||
const otherLabelValue = "other"
|
||||
|
||||
// assessmentMetrics count the saving of assessment answers, which PRD 6.6
|
||||
// names as a product signal next to API errors and queues. The answer
|
||||
// command (SubmitMyAssessmentAnswer) is not implemented yet, so nothing
|
||||
// calls the hook and no series exists; its HTTP latency and errors are
|
||||
// already counted per route template by the request metrics.
|
||||
type assessmentMetrics struct {
|
||||
answerSaves *client.CounterVec
|
||||
}
|
||||
|
||||
var (
|
||||
// answerFormats mirror the answer formats of the public contract.
|
||||
answerFormats = []string{"choice", "number", "string", "order", "find_error", "configuration", "practice"}
|
||||
// answerSaveOutcomes: stored (a new answer was stored), unchanged (the
|
||||
// same answer was already stored; nothing changed), rejected (a stale
|
||||
// version, a state conflict, or an invalid answer), or failed (an
|
||||
// internal error; nothing was stored).
|
||||
answerSaveOutcomes = []string{"stored", "unchanged", "rejected", "failed"}
|
||||
)
|
||||
|
||||
func newAssessmentMetrics() assessmentMetrics {
|
||||
return assessmentMetrics{
|
||||
answerSaves: client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_assessment_answer_saves_total",
|
||||
Help: "Assessment answer save commands by answer format and outcome: stored, unchanged, rejected, or failed.",
|
||||
}, []string{"format", "outcome"}),
|
||||
}
|
||||
}
|
||||
|
||||
func (assessment assessmentMetrics) collectors() []client.Collector {
|
||||
return []client.Collector{assessment.answerSaves}
|
||||
}
|
||||
|
||||
// ObserveAssessmentAnswerSave counts one answer save command. It is the hook
|
||||
// for the assessment usecase: call it once per command after its transaction
|
||||
// ended, with the format of the answer and one of the outcomes above. A
|
||||
// value outside these sets is counted as "other". Never pass an attempt,
|
||||
// item, or candidate identifier.
|
||||
func (metrics *Metrics) ObserveAssessmentAnswerSave(format, outcome string) {
|
||||
metrics.assessment.answerSaves.WithLabelValues(
|
||||
boundedLabel(format, answerFormats),
|
||||
boundedLabel(outcome, answerSaveOutcomes),
|
||||
).Inc()
|
||||
}
|
||||
|
||||
func boundedLabel(value string, allowed []string) string {
|
||||
if slices.Contains(allowed, value) {
|
||||
return value
|
||||
}
|
||||
return otherLabelValue
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
client "github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// mailMetrics describe the stored mail deliveries and the quota of the
|
||||
// configured provider account. Their labels come from closed sets: the
|
||||
// delivery kind and status from the domain, the transport name from
|
||||
// configuration, and the quota window. A recipient, address, user or
|
||||
// delivery ID, subject, and the provider account label never become labels;
|
||||
// the account label is free text an operator chooses, and one process
|
||||
// reports only its own configured account.
|
||||
type mailMetrics struct {
|
||||
// deliveries and oldestDuePendingAge are database-wide values at the
|
||||
// last statistics read. Every backend instance reports the same values,
|
||||
// so dashboards aggregate them with max. Both are vectors so that no
|
||||
// series exists before the first successful read: an age of 0 then would
|
||||
// claim that nothing is late.
|
||||
deliveries *client.GaugeVec
|
||||
oldestDuePendingAge *client.GaugeVec
|
||||
// lastSuccess is the Unix time of the last read in which every
|
||||
// aggregate was read; 0 from the sampler start until the first one.
|
||||
lastSuccess *client.GaugeVec
|
||||
// quotaUsed, quotaLimit, and quotaProviderExhausted describe the current
|
||||
// UTC day and month windows of the configured provider account.
|
||||
quotaUsed *client.GaugeVec
|
||||
quotaLimit *client.GaugeVec
|
||||
quotaProviderExhausted *client.GaugeVec
|
||||
}
|
||||
|
||||
// deliveryKinds and deliveryStatuses list the series that always exist, so a
|
||||
// status that empties drops to zero instead of keeping its last value.
|
||||
var (
|
||||
deliveryKinds = []domain.MailKind{
|
||||
domain.MailKindVerification,
|
||||
domain.MailKindPasswordReset,
|
||||
domain.MailKindNotification,
|
||||
}
|
||||
deliveryStatuses = []domain.DeliveryStatus{
|
||||
domain.DeliveryStatusPending,
|
||||
domain.DeliveryStatusWaitingQuota,
|
||||
domain.DeliveryStatusUnknown,
|
||||
domain.DeliveryStatusAccepted,
|
||||
domain.DeliveryStatusRejected,
|
||||
}
|
||||
)
|
||||
|
||||
func newMailMetrics() mailMetrics {
|
||||
return mailMetrics{
|
||||
deliveries: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_deliveries",
|
||||
Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted, or rejected.",
|
||||
}, []string{"kind", "status"}),
|
||||
oldestDuePendingAge: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_delivery_oldest_due_pending_age_seconds",
|
||||
Help: "How long the earliest pending delivery has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending deliveries, absent before the first read.",
|
||||
}, nil),
|
||||
lastSuccess: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_metrics_last_success_timestamp_seconds",
|
||||
Help: "Unix time of the last read of the delivery and quota aggregates in which every read succeeded; 0 from the sampler start until the first one.",
|
||||
}, nil),
|
||||
quotaUsed: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_quota_used_recipients",
|
||||
Help: "Recipients counted against the current UTC window of the configured provider account, by provider and window: day or month.",
|
||||
}, []string{"provider", "window"}),
|
||||
quotaLimit: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_quota_limit_recipients",
|
||||
Help: "Configured recipient limit of the current UTC window, by provider and window: day or month.",
|
||||
}, []string{"provider", "window"}),
|
||||
quotaProviderExhausted: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_quota_provider_exhausted",
|
||||
Help: "1 when the provider itself reported the quota of the current UTC window used up, 0 otherwise, by provider and window.",
|
||||
}, []string{"provider", "window"}),
|
||||
}
|
||||
}
|
||||
|
||||
func (mail mailMetrics) collectors() []client.Collector {
|
||||
return []client.Collector{
|
||||
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
|
||||
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
|
||||
}
|
||||
}
|
||||
|
||||
type deliveryState struct {
|
||||
kind domain.MailKind
|
||||
status domain.DeliveryStatus
|
||||
}
|
||||
|
||||
// ObserveDeliveryStates records the latest delivery statistics read. Every
|
||||
// known kind and status pair is set, to zero when counts has none.
|
||||
func (metrics *Metrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldestDuePending time.Duration) {
|
||||
values := make(map[deliveryState]int64, len(deliveryKinds)*len(deliveryStatuses))
|
||||
for _, kind := range deliveryKinds {
|
||||
for _, status := range deliveryStatuses {
|
||||
values[deliveryState{kind: kind, status: status}] = 0
|
||||
}
|
||||
}
|
||||
// The store parses kind and status into domain values, so a value the
|
||||
// lists above do not know yet is still bounded.
|
||||
for _, count := range counts {
|
||||
values[deliveryState{kind: count.Kind, status: count.Status}] += count.Deliveries
|
||||
}
|
||||
for state, value := range values {
|
||||
metrics.mail.deliveries.WithLabelValues(string(state.kind), string(state.status)).Set(float64(value))
|
||||
}
|
||||
metrics.mail.oldestDuePendingAge.WithLabelValues().Set(oldestDuePending.Seconds())
|
||||
}
|
||||
|
||||
// PrepareMailMetricsReads exposes the last success time at 0 when the
|
||||
// sampler starts, so an alert sees a sampler that never reads successfully.
|
||||
func (metrics *Metrics) PrepareMailMetricsReads() {
|
||||
metrics.mail.lastSuccess.WithLabelValues().Set(0)
|
||||
}
|
||||
|
||||
// ObserveMailMetricsReadSuccess records a read in which every aggregate was
|
||||
// read.
|
||||
func (metrics *Metrics) ObserveMailMetricsReadSuccess(at time.Time) {
|
||||
metrics.mail.lastSuccess.WithLabelValues().Set(float64(at.UnixNano()) / float64(time.Second))
|
||||
}
|
||||
|
||||
// ObserveMailQuota records the usage of the current windows of the
|
||||
// configured account of provider, a transport name from configuration.
|
||||
func (metrics *Metrics) ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits) {
|
||||
windows := []struct {
|
||||
period domain.MailQuotaPeriod
|
||||
used int64
|
||||
exhausted time.Time
|
||||
}{
|
||||
{period: domain.MailQuotaPeriodDay, used: usage.DayUsed, exhausted: usage.DayProviderExhaustedAt},
|
||||
{period: domain.MailQuotaPeriodMonth, used: usage.MonthUsed, exhausted: usage.MonthProviderExhaustedAt},
|
||||
}
|
||||
for _, window := range windows {
|
||||
labels := []string{provider, string(window.period)}
|
||||
metrics.mail.quotaUsed.WithLabelValues(labels...).Set(float64(window.used))
|
||||
metrics.mail.quotaLimit.WithLabelValues(labels...).Set(float64(limits.Of(window.period)))
|
||||
exhausted := 0.0
|
||||
if !window.exhausted.IsZero() {
|
||||
exhausted = 1
|
||||
}
|
||||
metrics.mail.quotaProviderExhausted.WithLabelValues(labels...).Set(exhausted)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,11 @@ import (
|
||||
type Metrics struct {
|
||||
registry *client.Registry
|
||||
requests *client.CounterVec
|
||||
latency *client.HistogramVec
|
||||
// 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.
|
||||
@@ -40,6 +44,9 @@ type Metrics struct {
|
||||
scheduledJobsDue client.Gauge
|
||||
scheduledJobsOldestDueAge client.Gauge
|
||||
scheduledJobsDead client.Gauge
|
||||
|
||||
mail mailMetrics
|
||||
assessment assessmentMetrics
|
||||
}
|
||||
|
||||
// Outbox relay outcome label values.
|
||||
@@ -65,9 +72,13 @@ func New() *Metrics {
|
||||
}, []string{"method", "route", "status"})
|
||||
latency := client.NewHistogramVec(client.HistogramOpts{
|
||||
Name: "lincodex_http_request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Help: "HTTP request duration in seconds, by method, route template, and status class.",
|
||||
Buckets: client.DefBuckets,
|
||||
}, []string{"method", "route"})
|
||||
}, []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.",
|
||||
@@ -104,13 +115,17 @@ func New() *Metrics {
|
||||
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, relayEvents, relayPending, relayOldestAge,
|
||||
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)
|
||||
@@ -118,6 +133,7 @@ func New() *Metrics {
|
||||
registry: registry,
|
||||
requests: requests,
|
||||
latency: latency,
|
||||
problems: problems,
|
||||
relayEvents: relayEvents,
|
||||
relayPending: relayPending,
|
||||
relayOldestAge: relayOldestAge,
|
||||
@@ -129,6 +145,9 @@ func New() *Metrics {
|
||||
scheduledJobsDue: scheduledJobsDue,
|
||||
scheduledJobsOldestDueAge: scheduledJobsOldestDueAge,
|
||||
scheduledJobsDead: scheduledJobsDead,
|
||||
|
||||
mail: mail,
|
||||
assessment: assessment,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +220,36 @@ func (metrics *Metrics) ObserveRequest(method, route string, status int, duratio
|
||||
method = "OTHER"
|
||||
}
|
||||
metrics.requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
|
||||
metrics.latency.WithLabelValues(method, route).Observe(duration.Seconds())
|
||||
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",
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
|
||||
if !strings.Contains(body, `lincodex_http_requests_total{method="OTHER",route="unmatched",status="599"} 1`) {
|
||||
t.Fatalf("metrics output is missing bounded request labels:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",le="0.05"} 1`) {
|
||||
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",status_class="5xx",le="0.05"} 1`) {
|
||||
t.Fatalf("metrics output is missing request duration:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/pkg/testutil"
|
||||
)
|
||||
|
||||
func scrape(t *testing.T, metrics *Metrics) string {
|
||||
t.Helper()
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
return response.Body.String()
|
||||
}
|
||||
|
||||
func requireSeries(t *testing.T, body string, want ...string) {
|
||||
t.Helper()
|
||||
for _, series := range want {
|
||||
if !strings.Contains(body, series+"\n") {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", series, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesProblemsAndLatencyByStatusClass(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveRequest("GET", "/api/v1/healthz", 200, 3*time.Millisecond)
|
||||
metrics.ObserveRequest("GET", "/api/v1/*", 404, time.Millisecond)
|
||||
metrics.ObserveProblem("/api/v1/*", "not_found")
|
||||
metrics.ObserveProblem("", "internal")
|
||||
|
||||
requireSeries(t, scrape(t, metrics),
|
||||
`lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/healthz",status_class="2xx"} 1`,
|
||||
`lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/*",status_class="4xx"} 1`,
|
||||
`lincodex_http_problems_total{code="not_found",route="/api/v1/*"} 1`,
|
||||
`lincodex_http_problems_total{code="internal",route="unmatched"} 1`,
|
||||
)
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesEveryDeliveryState(t *testing.T) {
|
||||
metrics := New()
|
||||
// Before the first read nothing claims that no delivery is late.
|
||||
if body := scrape(t, metrics); strings.Contains(body, "lincodex_mail_delivery_oldest_due_pending_age_seconds ") ||
|
||||
strings.Contains(body, "lincodex_mail_deliveries{") {
|
||||
t.Fatalf("delivery series exist before the first read:\n%s", body)
|
||||
}
|
||||
metrics.ObserveDeliveryStates([]outbound.DeliveryStatusCount{
|
||||
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 3},
|
||||
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusUnknown, Deliveries: 1},
|
||||
}, 90*time.Second)
|
||||
requireSeries(t, scrape(t, metrics),
|
||||
`lincodex_mail_deliveries{kind="verification",status="pending"} 3`,
|
||||
`lincodex_mail_deliveries{kind="notification",status="unknown"} 1`,
|
||||
// Every known pair exists at zero.
|
||||
`lincodex_mail_deliveries{kind="password_reset",status="waiting_quota"} 0`,
|
||||
`lincodex_mail_deliveries{kind="verification",status="accepted"} 0`,
|
||||
`lincodex_mail_deliveries{kind="notification",status="rejected"} 0`,
|
||||
"lincodex_mail_delivery_oldest_due_pending_age_seconds 90",
|
||||
)
|
||||
|
||||
// A status that emptied drops to zero instead of keeping its value.
|
||||
metrics.ObserveDeliveryStates(nil, 0)
|
||||
requireSeries(t, scrape(t, metrics),
|
||||
`lincodex_mail_deliveries{kind="verification",status="pending"} 0`,
|
||||
`lincodex_mail_deliveries{kind="notification",status="unknown"} 0`,
|
||||
"lincodex_mail_delivery_oldest_due_pending_age_seconds 0",
|
||||
)
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesMailQuotaWithoutTheAccount(t *testing.T) {
|
||||
limits, err := domain.NewMailQuotaLimits(100, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
metrics := New()
|
||||
metrics.ObserveMailQuota("resend", outbound.MailQuotaUsage{
|
||||
DayUsed: 100,
|
||||
MonthUsed: 1250,
|
||||
DayProviderExhaustedAt: time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC),
|
||||
}, limits)
|
||||
body := scrape(t, metrics)
|
||||
requireSeries(t, body,
|
||||
`lincodex_mail_quota_used_recipients{provider="resend",window="day"} 100`,
|
||||
`lincodex_mail_quota_used_recipients{provider="resend",window="month"} 1250`,
|
||||
`lincodex_mail_quota_limit_recipients{provider="resend",window="day"} 100`,
|
||||
`lincodex_mail_quota_limit_recipients{provider="resend",window="month"} 3000`,
|
||||
`lincodex_mail_quota_provider_exhausted{provider="resend",window="day"} 1`,
|
||||
`lincodex_mail_quota_provider_exhausted{provider="resend",window="month"} 0`,
|
||||
)
|
||||
if strings.Contains(body, "account=") {
|
||||
t.Fatalf("quota metrics carry an account label:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAnswerSaveHookBoundsItsLabels(t *testing.T) {
|
||||
metrics := New()
|
||||
if body := scrape(t, metrics); strings.Contains(body, "lincodex_assessment_answer_saves_total{") {
|
||||
t.Fatalf("answer save series exist before the hook was called:\n%s", body)
|
||||
}
|
||||
metrics.ObserveAssessmentAnswerSave("choice", "stored")
|
||||
metrics.ObserveAssessmentAnswerSave("practice", "unchanged")
|
||||
// A caller mistake must not create a series per value.
|
||||
metrics.ObserveAssessmentAnswerSave("0199b4f2-7c1e-7d3a-9f00-aabbccddeeff", "jane@example.com")
|
||||
requireSeries(t, scrape(t, metrics),
|
||||
`lincodex_assessment_answer_saves_total{format="choice",outcome="stored"} 1`,
|
||||
`lincodex_assessment_answer_saves_total{format="practice",outcome="unchanged"} 1`,
|
||||
`lincodex_assessment_answer_saves_total{format="other",outcome="other"} 1`,
|
||||
)
|
||||
}
|
||||
|
||||
// TestRegisteredMetricsCarryNoPersonalIdentifiers exercises every hook of the
|
||||
// adapter, including values that look like the identifiers a careless caller
|
||||
// could pass, and scans the whole exposition, label names and values
|
||||
// included, for an email address or a UUID.
|
||||
func TestRegisteredMetricsCarryNoPersonalIdentifiers(t *testing.T) {
|
||||
const (
|
||||
fixtureEmail = "metrics.fixture@example.com"
|
||||
fixtureID = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"
|
||||
)
|
||||
limits, err := domain.NewMailQuotaLimits(100, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
metrics := New()
|
||||
metrics.ObserveRequest("GET", "/api/v1/me/invitations/{invitationId}", 401, time.Millisecond)
|
||||
metrics.ObserveProblem("/api/v1/me/invitations/{invitationId}", "unauthenticated")
|
||||
metrics.ObserveOutboxRelayPass(2, 1)
|
||||
metrics.ObserveOutboxBacklog(outbound.OutboxBacklog{Pending: 1, OldestAge: time.Second})
|
||||
metrics.PrepareEventConsumer("mail_delivery")
|
||||
metrics.ObserveConsumedRecord("mail_delivery", "applied")
|
||||
metrics.ObserveConsumerFailure("mail_delivery", "handler")
|
||||
metrics.PrepareScheduledJobKind("invitation.response_deadline")
|
||||
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
|
||||
metrics.ObserveScheduledJobBacklog(outbound.JobBacklog{Due: 1})
|
||||
metrics.ObserveDeliveryStates([]outbound.DeliveryStatusCount{
|
||||
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusAccepted, Deliveries: 1},
|
||||
}, time.Minute)
|
||||
metrics.ObserveMailQuota("resend", outbound.MailQuotaUsage{DayUsed: 1, MonthUsed: 1}, limits)
|
||||
metrics.PrepareMailMetricsReads()
|
||||
metrics.ObserveMailMetricsReadSuccess(time.Now())
|
||||
metrics.ObserveAssessmentAnswerSave(fixtureEmail, fixtureID)
|
||||
|
||||
body := scrape(t, metrics)
|
||||
if found := testutil.FindPersonalIdentifiers(body); len(found) != 0 {
|
||||
t.Fatalf("metrics expose identifiers %q:\n%s", found, body)
|
||||
}
|
||||
for _, marker := range []string{fixtureEmail, fixtureID, "@"} {
|
||||
if strings.Contains(body, marker) {
|
||||
t.Fatalf("metrics expose %q:\n%s", marker, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesTheLastSuccessfulMailMetricsRead(t *testing.T) {
|
||||
metrics := New()
|
||||
if body := scrape(t, metrics); strings.Contains(body, "lincodex_mail_metrics_last_success_timestamp_seconds ") {
|
||||
t.Fatalf("the last success time exists without a sampler:\n%s", body)
|
||||
}
|
||||
metrics.PrepareMailMetricsReads()
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_metrics_last_success_timestamp_seconds 0")
|
||||
metrics.ObserveMailMetricsReadSuccess(time.Unix(1791290638, 500_000_000))
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_metrics_last_success_timestamp_seconds 1.7912906385e+09")
|
||||
}
|
||||
|
||||
func TestProblemCodesOutsideTheCatalogueAreBounded(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveProblem("/api/v1/*", "jane@example.com")
|
||||
requireSeries(t, scrape(t, metrics), `lincodex_http_problems_total{code="other",route="/api/v1/*"} 1`)
|
||||
}
|
||||
Reference in new issue
Block a user