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

219 lines
9.9 KiB
Go

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
// senderRunning is 1 while this process's mail sending loop runs. It is
// per process, not database-wide, so dashboards and alerts aggregate it
// with max across instances.
senderRunning client.Gauge
// senderCancelled counts deliveries that the sending worker ended without
// sending, by cancel reason, a closed set from the domain.
senderCancelled *client.CounterVec
// identityRateLimited counts identity requests the limiter refused, by
// scope: address, client, or token. No address, email, or key is a label.
identityRateLimited *client.CounterVec
}
// 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,
domain.DeliveryStatusCancelled,
}
)
func newMailMetrics() mailMetrics {
metrics := 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 (by the provider, not delivered to a person), rejected, or cancelled.",
}, []string{"kind", "status"}),
oldestDuePendingAge: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_delivery_oldest_due_pending_age_seconds",
Help: "How long the earliest pending service mail (verification or password reset, the kinds the sending worker handles) has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending service mail, absent before the first read. Notifications are not counted until they are sent.",
}, 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"}),
senderCancelled: client.NewCounterVec(client.CounterOpts{
Name: "lincodex_mail_sender_cancelled_total",
Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.",
}, []string{"reason"}),
identityRateLimited: client.NewCounterVec(client.CounterOpts{
Name: "lincodex_identity_rate_limit_refusals_total",
Help: "Identity requests refused with 429 by the limiter, by scope: address (per email address), client (per network address), or token (per verification token). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.",
}, []string{"scope"}),
senderRunning: client.NewGauge(client.GaugeOpts{
Name: "lincodex_mail_sender_running",
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
}),
}
// Every reason exists at zero, so an alert on an increase sees the first
// cancellation instead of a new series.
for _, reason := range domain.DeliveryCancelReasons() {
metrics.senderCancelled.WithLabelValues(string(reason))
}
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient, IdentityScopeToken} {
metrics.identityRateLimited.WithLabelValues(scope)
}
return metrics
}
// The scopes of the identity rate limit refusal counter.
const (
IdentityScopeAddress = "address"
IdentityScopeClient = "client"
IdentityScopeToken = "token"
)
// ObserveIdentityRateLimited counts one refused identity request. A scope
// outside the known scopes counts as address, so the label stays bounded.
func (metrics *Metrics) ObserveIdentityRateLimited(scope string) {
if scope != IdentityScopeClient && scope != IdentityScopeToken {
scope = IdentityScopeAddress
}
metrics.mail.identityRateLimited.WithLabelValues(scope).Inc()
}
func (mail mailMetrics) collectors() []client.Collector {
return []client.Collector{
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
mail.senderRunning, mail.senderCancelled, mail.identityRateLimited,
}
}
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())
}
// ObserveMailCancelled counts one cancelled delivery by its cancel reason. A
// reason outside the domain set counts as processing_failed, so the label stays
// bounded.
func (metrics *Metrics) ObserveMailCancelled(reason string) {
if _, err := domain.ParseDeliveryCancelReason(reason); err != nil {
reason = string(domain.DeliveryCancelProcessingFailed)
}
metrics.mail.senderCancelled.WithLabelValues(reason).Inc()
}
// SetMailSenderRunning reports whether this process's mail sending loop
// runs: 1 from the moment it starts until it stops, 0 otherwise. The series
// exists at 0 from startup, also when the loop never starts.
func (metrics *Metrics) SetMailSenderRunning(running bool) {
value := 0.0
if running {
value = 1
}
metrics.mail.senderRunning.Set(value)
}
// 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)
}
}