feat(mail): send service identity mail through a leased worker

This commit is contained in:
shira committed 2026-10-06 21:08:11 +03:00
1 parent 204c6bae62
commit d21fd49a42
58 files changed
+7577 -164

No files matched your search

@@ -32,6 +32,13 @@ type mailMetrics struct {
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
}
// deliveryKinds and deliveryStatuses list the series that always exist, so a
@@ -48,18 +55,19 @@ var (
domain.DeliveryStatusUnknown,
domain.DeliveryStatusAccepted,
domain.DeliveryStatusRejected,
domain.DeliveryStatusCancelled,
}
)
func newMailMetrics() mailMetrics {
return 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, or rejected.",
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 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.",
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",
@@ -77,13 +85,28 @@ func newMailMetrics() mailMetrics {
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"}),
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))
}
return metrics
}
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,
}
}
@@ -112,6 +135,27 @@ func (metrics *Metrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCo
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() {
@@ -0,0 +1,41 @@
package prometheus
import (
"strings"
"testing"
)
func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) {
metrics := New()
// The series exists before any loop starts, so an alert that needs
// "the sender runs" sees 0 instead of a missing series.
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
metrics.SetMailSenderRunning(true)
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 1")
metrics.SetMailSenderRunning(false)
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
}
func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
metrics := New()
// Every reason exists at zero before the first cancellation.
body := scrape(t, metrics)
requireSeries(t, body,
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 0`,
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 0`,
`lincodex_mail_sender_cancelled_total{reason="token_revoked"} 0`,
)
metrics.ObserveMailCancelled("content_invalid")
metrics.ObserveMailCancelled("content_invalid")
// A reason outside the domain set cannot become a label.
metrics.ObserveMailCancelled("someone@example.com")
requireSeries(t, scrape(t, metrics),
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 2`,
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 1`,
)
if strings.Contains(scrape(t, metrics), "someone@example.com") {
t.Fatal("an arbitrary reason became a label")
}
}
@@ -60,6 +60,7 @@ func TestMetricsHandlerExposesEveryDeliveryState(t *testing.T) {
`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_deliveries{kind="verification",status="cancelled"} 0`,
"lincodex_mail_delivery_oldest_due_pending_age_seconds 90",
)