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

+19 -7
View File
@@ -20,6 +20,7 @@ import (
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/deliverymetrics"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/mailsender"
"lincodex/backend/internal/worker/outboxrelay"
)
@@ -33,8 +34,8 @@ type Application struct {
apiHandler http.Handler
metrics *prometheus.Metrics
logger *slog.Logger
// mailSender is the transport selected by EMAIL_PROVIDER. No usecase
// sends mail yet; the delivery layer will take it from here.
// mailSender is the transport selected by EMAIL_PROVIDER. Only the mail
// sending worker calls it.
mailSender outbound.MailSender
// relay publishes outbox events while the servers run. It is nil when
// the relay is disabled or the database is not configured.
@@ -46,6 +47,10 @@ type Application struct {
// is nil when the worker is disabled, no job kind is registered, or the
// database is not configured.
jobs *jobrunner.Worker
// mailSending sends the stored service mail of the account flows while
// the servers run. It is nil with EMAIL_PROVIDER=disabled or when the
// database is not configured.
mailSending *mailsender.Worker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
@@ -60,6 +65,7 @@ func NewApplication(
relay *outboxrelay.Relay,
consumers eventConsumers,
jobs *jobrunner.Worker,
mailSending *mailsender.Worker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
@@ -71,6 +77,7 @@ func NewApplication(
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
deliveryMetrics: deliveryMetrics,
}
}
@@ -189,16 +196,18 @@ func (application *Application) run(ctx context.Context) error {
stopRun()
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, each
// consumer its record in progress within CONSUMER_SHUTDOWN_GRACE plus
// one offset commit, and the job worker its job in progress within
// JOBS_SHUTDOWN_GRACE plus one release, so the cleanup that closes their
// pools, producer, and group members runs after all of them stopped.
// one offset commit, the job worker its job in progress within
// JOBS_SHUTDOWN_GRACE plus one release, and the mail sending worker its
// send in progress within its shutdown grace plus one settlement, so the
// cleanup that closes their pools, producer, and group members runs after
// all of them stopped.
<-workersStopped
application.logger.Info("workers stopped")
return err
}
// startWorkers runs the relay, every consumer, the scheduled job worker, and
// the delivery metrics sampler until ctx ends and returns a channel that
// startWorkers runs the relay, every consumer, the scheduled job worker, the
// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that
// closes when all of them have stopped. The workers stop together with the
// servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
@@ -212,6 +221,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.jobs != nil {
workers.Go(func() { application.jobs.Run(ctx) })
}
if application.mailSending != nil {
workers.Go(func() { application.mailSending.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
+1 -1
View File
@@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -63,7 +63,7 @@ func TestApplicationRunsAndStopsTheDeliveryMetricsSampler(t *testing.T) {
if sampler == nil {
t.Fatal("newDeliveryMetrics() built no sampler with DATABASE_URL set")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, sampler)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -87,7 +87,7 @@ func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+154
View File
@@ -0,0 +1,154 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/worker/mailsender"
"lincodex/backend/internal/worker/retry"
)
const (
// mailSenderPoolMaxConns covers the claim or settlement transaction of
// the loop, which run one after another, and one statement next to it.
mailSenderPoolMaxConns = 2
// mailSenderPollInterval is the wait after a pass that found nothing
// due. A verification mail is something a person waits for, so the wait
// is short; an idle pass is one indexed statement.
mailSenderPollInterval = 5 * time.Second
// mailSenderStoreTimeout bounds the claim transaction and each try to
// store a send result.
mailSenderStoreTimeout = 15 * time.Second
// mailSenderLeaseMargin is added to EMAIL_TIMEOUT to give the lease on a
// claimed delivery: the attempt, the settlement, and some slack. A lease
// is long enough that a live sender never loses it, and short enough that
// a delivery of a stopped sender is taken over within minutes.
mailSenderLeaseMargin = time.Minute
// mailSenderShutdownGrace is how long a send in progress may continue
// after shutdown began; its result is stored anyway.
mailSenderShutdownGrace = 3 * time.Second
// mailSenderSettleBudget bounds storing the answer of a send, retries
// included. It is reserved inside the lease, so the call plus this budget
// plus the claim fit in EMAIL_TIMEOUT plus mailSenderLeaseMargin.
mailSenderSettleBudget = 20 * time.Second
// mailSenderMaxShutdownSettle bounds storing an answer once shutdown began;
// the grace plus this must fit SHUTDOWN_TIMEOUT, so the budget is shortened
// when that is set lower (bootstrap.shutdownSettleBudget).
mailSenderMaxShutdownSettle = 5 * time.Second
// mailSenderMaxFailures is how many consecutive failures of the worker on
// one delivery are retried before it is cancelled as processing_failed.
mailSenderMaxFailures = 3
// mailSenderRetryInitial and mailSenderRetryMax pace the repeat of an
// attempt that the provider refused for now (temporary or rate limited):
// one minute, doubling, at most half an hour; a longer Retry-After from
// the provider is honored as it is.
mailSenderRetryInitial = time.Minute
mailSenderRetryMax = 30 * time.Minute
// mailSenderBackoffInitial and mailSenderBackoffMax pace the loop after a
// database failure or a pass that could not send.
mailSenderBackoffInitial = 5 * time.Second
mailSenderBackoffMax = 2 * time.Minute
)
var _ mailsender.Metrics = (*prometheus.Metrics)(nil)
// newMailSenderWorker builds the sending loop of the service identity mail
// and the PostgreSQL pool it owns. Nothing connects here, so an unavailable
// database never blocks startup; the loop retries in the background.
//
// It returns no worker, and lincodex_mail_sender_running stays 0, when
// EMAIL_PROVIDER=disabled, because that transport sends nothing and a loop
// that claims deliveries only to find the channel unavailable would count
// quota reservations and wake the database for no effect; the stored
// deliveries wait, pinned to disabled, until a restart with a transport.
// It returns none either when DATABASE_URL is unset. The application clock is
// time.Now.
func newMailSenderWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
mailSender outbound.MailSender,
) (*mailsender.Worker, func(), error) {
switch {
case settings.EmailProvider == config.EmailProviderDisabled:
logger.Info("mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("mail sender worker skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - provider account: %w", err)
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - quota limits: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, mailSenderPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create pool: %w", err)
}
workerLogger := logger.With(slog.String("component", "mail_sender"))
gate := notification.NewQuotaGate(account, limits, mailIdempotencyWindow(settings), time.Now, workerLogger)
sender, err := notification.NewServiceMailSender(
postgres.NewTransactor(pool),
mailSender,
gate,
notification.ServiceMailSenderSettings{
Account: account,
RebindProvider: string(config.EmailProviderDisabled),
Lease: settings.EmailTimeout + mailSenderLeaseMargin,
StoreTimeout: mailSenderStoreTimeout,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: shutdownSettleBudget(settings.ShutdownTimeout),
MaxFailures: mailSenderMaxFailures,
Retry: notification.RetryPolicy{Initial: mailSenderRetryInitial, Max: mailSenderRetryMax, Jitter: notification.RandomJitter},
},
time.Now,
workerLogger,
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create sender: %w", err)
}
worker, err := mailsender.New(sender, metrics, workerLogger, mailsender.Settings{
PollInterval: mailSenderPollInterval,
Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax},
ShutdownGrace: mailSenderShutdownGrace,
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create worker: %w", err)
}
// The application stops the worker before this cleanup runs, so no send
// uses the pool while it closes.
return worker, pool.Close, nil
}
// shutdownSettleBudget is the time to store the answer of a send once shutdown
// began: what SHUTDOWN_TIMEOUT leaves after the shutdown grace, at most
// mailSenderMaxShutdownSettle and at least one second.
func shutdownSettleBudget(shutdownTimeout time.Duration) time.Duration {
return min(mailSenderMaxShutdownSettle, max(shutdownTimeout-mailSenderShutdownGrace, time.Second))
}
// mailIdempotencyWindow is how long the selected transport's provider
// deduplicates a repeated request with the same idempotency key; zero for a
// transport without provider-side deduplication.
func mailIdempotencyWindow(settings config.Config) time.Duration {
if settings.EmailProvider == config.EmailProviderResend {
return resend.IdempotencyWindow
}
return 0
}
@@ -0,0 +1,146 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
// resendSenderConfig is a Resend setup with a database that does not answer.
func resendSenderConfig(t *testing.T) config.Config {
t.Helper()
settings := consumerTestConfig(t)
settings.EmailProvider = config.EmailProviderResend
settings.EmailAccount = "primary"
settings.EmailTimeout = 10 * time.Second
settings.EmailQuotaDaily = 100
settings.EmailQuotaMonthly = 3000
return settings
}
func TestNewMailSenderWorkerSkipsWithoutWork(t *testing.T) {
noDatabase := resendSenderConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
log string
}{
// consumerTestConfig selects the disabled transport.
{name: "transport disabled", settings: consumerTestConfig(t), log: "EMAIL_PROVIDER is disabled"},
{name: "database not configured", settings: noDatabase, log: "DATABASE_URL is not set"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var logs strings.Builder
logger := slog.New(slog.NewTextHandler(&logs, nil))
metrics := prometheus.New()
worker, cleanup, err := newMailSenderWorker(t.Context(), test.settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newMailSenderWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("newMailSenderWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
// Without a loop the gauge says so, so the overdue alert stays
// silent.
if body := scrape(metrics); !strings.Contains(body, "lincodex_mail_sender_running 0\n") {
t.Fatalf("metrics lack lincodex_mail_sender_running 0:\n%s", body)
}
})
}
}
func TestMailIdempotencyWindowFollowsTheTransport(t *testing.T) {
if got := mailIdempotencyWindow(config.Config{EmailProvider: config.EmailProviderResend}); got != resend.IdempotencyWindow {
t.Fatalf("mailIdempotencyWindow(resend) = %s, want %s", got, resend.IdempotencyWindow)
}
// A relay has no provider-side deduplication, so every retry counts again.
if got := mailIdempotencyWindow(config.Config{EmailProvider: config.EmailProviderSMTP}); got != 0 {
t.Fatalf("mailIdempotencyWindow(smtp) = %s, want 0", got)
}
}
// TestApplicationRunsAndStopsTheMailSenderWorker starts the loop against a
// database that does not answer: it backs off in the background, reports
// that it runs, and the application still stops within its shutdown budget
// with the gauge back at 0.
func TestApplicationRunsAndStopsTheMailSenderWorker(t *testing.T) {
settings := resendSenderConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
worker, cleanup, err := newMailSenderWorker(t.Context(), settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newMailSenderWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("newMailSenderWorker() built no worker for an active transport")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
deadline := time.Now().Add(relayLifecycleTimeout)
for !strings.Contains(scrape(metrics), "lincodex_mail_sender_running 1\n") {
if time.Now().After(deadline) {
t.Fatal("the loop never reported that it runs")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
if body := scrape(metrics); !strings.Contains(body, "lincodex_mail_sender_running 0\n") {
t.Fatalf("the gauge did not return to 0 after the loop stopped:\n%s", body)
}
}
func scrape(metrics *prometheus.Metrics) string {
recorder := httptest.NewRecorder()
metrics.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil))
return recorder.Body.String()
}
func TestShutdownSettleBudgetFitsTheShutdownTimeout(t *testing.T) {
for _, test := range []struct {
shutdown time.Duration
want time.Duration
}{
{30 * time.Second, mailSenderMaxShutdownSettle},
{10 * time.Second, mailSenderMaxShutdownSettle}, // the default SHUTDOWN_TIMEOUT
{6 * time.Second, 3 * time.Second},
{time.Second, time.Second},
} {
got := shutdownSettleBudget(test.shutdown)
if got != test.want {
t.Fatalf("shutdownSettleBudget(%s) = %s, want %s", test.shutdown, got, test.want)
}
if test.shutdown >= 4*time.Second && mailSenderShutdownGrace+got > test.shutdown {
t.Fatalf("grace plus settle budget = %s, over SHUTDOWN_TIMEOUT %s", mailSenderShutdownGrace+got, test.shutdown)
}
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -50,6 +50,7 @@ func initialize(
newOutboxRelay,
newEventConsumers,
newJobWorker,
newMailSenderWorker,
newDeliveryMetrics,
NewApplication,
),
+14 -2
View File
@@ -79,7 +79,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup7, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup7, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup6()
cleanup5()
@@ -89,8 +89,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, sampler)
sampler, cleanup8, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup8()
cleanup7()
cleanup6()
cleanup5()