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

@@ -0,0 +1,187 @@
// Package mailsender runs the sending loop of the service identity mail:
// it repeats passes of the sending usecase until it is stopped, waits when
// nothing is due, and backs off when a pass fails, so it never spins on a
// persistent failure. Several workers may run against one database, in one
// process or many; the claim in the usecase keeps them off each other's
// deliveries.
package mailsender
import (
"context"
"errors"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/worker/retry"
)
// rowStreakLimit is how many passes in a row may fail on different rows
// before the failures stop being counted against rows.
const rowStreakLimit = 3
// Metrics exposes whether the sending loop runs. The alert on overdue
// deliveries needs it: a delivery that waits while no sender runs is a
// different problem from one that waits while a sender runs.
type Metrics interface {
// SetMailSenderRunning reports 1 while the loop runs and 0 otherwise.
SetMailSenderRunning(running bool)
// ObserveMailCancelled counts a delivery that the worker ended without
// sending, by its cancel reason, a closed set. content_invalid and
// processing_failed point at a defect or a broken row and are alerted on.
ObserveMailCancelled(reason string)
}
// Settings are the named limits of the loop.
type Settings struct {
// PollInterval is the wait after a pass that found no due delivery.
PollInterval time.Duration
// Backoff is the wait after a pass that failed in the database and after
// a pass that sent nothing because no transport is active or the call was
// interrupted; it grows across consecutive failures.
Backoff retry.Backoff
// ShutdownGrace is how long a send in progress may continue after Run's
// context ends. When it expires the call is canceled; the result is
// stored anyway.
ShutdownGrace time.Duration
}
func (settings Settings) validate() error {
if settings.PollInterval <= 0 || settings.ShutdownGrace <= 0 || settings.Backoff.Initial <= 0 || settings.Backoff.Max < settings.Backoff.Initial {
return errors.New("mailsender.New - poll interval, shutdown grace, and backoff must be positive, and the maximum backoff not below the initial one")
}
return nil
}
// Worker repeats passes of the sending usecase.
type Worker struct {
pass inbound.MailPass
metrics Metrics
logger *slog.Logger
settings Settings
}
// New builds a worker around the sending usecase.
func New(pass inbound.MailPass, metrics Metrics, logger *slog.Logger, settings Settings) (*Worker, error) {
if err := settings.validate(); err != nil {
return nil, err
}
return &Worker{pass: pass, metrics: metrics, logger: logger, settings: settings}, nil
}
// Run sends due mail until ctx ends. A pass that handled a delivery is
// followed at once by the next one, because more may be due; after an idle
// pass the worker waits PollInterval. After a database failure, a missing
// transport, or an interrupted call it waits Backoff, which grows with every
// consecutive failure. Run claims nothing once ctx ends, lets a send in
// progress continue for ShutdownGrace, stores its result, and returns.
// lincodex_mail_sender_running is 1 while it loops.
func (worker *Worker) Run(ctx context.Context) {
workCtx, stopWork := worker.workContext(ctx)
defer stopWork()
worker.metrics.SetMailSenderRunning(true)
defer worker.metrics.SetMailSenderRunning(false)
worker.logger.Info("mail sender worker started", slog.Duration("poll_interval", worker.settings.PollInterval))
defer worker.logger.Info("mail sender worker stopped")
failures := 0
// rowStreak counts consecutive passes that failed on a row, each on a
// different row than the one before. Failures that hit row after row do not
// say that rows are broken but that something around them is, so they stop
// being counted against rows (the breaker) until a pass succeeds.
breaker := rowBreaker{pass: worker.pass}
defer worker.pass.PauseFailureCounting(false)
for ctx.Err() == nil {
result, err := worker.pass.ProcessNext(ctx, workCtx)
if err == nil && result.Outcome == inbound.MailPassCancelled {
worker.metrics.ObserveMailCancelled(string(result.CancelReason))
}
var delay time.Duration
rowStreak := breaker.observe(result, err)
switch {
case ctx.Err() != nil:
return
case err != nil:
failures++
delay = worker.settings.Backoff.Delay(failures)
worker.logger.Warn("mail sender pass failed in the database; the delivery waits under its lease",
slog.Int("consecutive_failures", failures),
slog.Duration("retry_in", delay),
slog.Any("error", err))
case result.Outcome == inbound.MailPassChannelUnavailable || result.Outcome == inbound.MailPassInterrupted:
failures++
delay = worker.settings.Backoff.Delay(failures)
worker.logger.Warn("mail was not sent because no transport is active or the call was interrupted; the delivery stays due",
slog.String("outcome", string(result.Outcome)),
slog.Int("consecutive_failures", failures),
slog.Duration("retry_in", delay))
case result.Outcome == inbound.MailPassRowFailed:
// A failing row has left the head of the queue, but a tight loop
// over many of them is what the breaker exists to stop: wait,
// longer the longer it goes on.
delay = worker.settings.Backoff.Delay(max(rowStreak, 1))
worker.logger.Warn("mail sender pass failed on a delivery; it is retried later",
slog.Int("rows_in_a_row", rowStreak),
slog.Bool("counting_paused", rowStreak >= rowStreakLimit),
slog.Duration("retry_in", delay))
case result.Outcome == inbound.MailPassIdle:
failures = 0
delay = worker.settings.PollInterval
default:
failures = 0
}
if !retry.Wait(ctx, delay) {
return
}
}
}
// rowBreaker is the circuit breaker over failures that hit row after row.
type rowBreaker struct {
pass inbound.MailPass
streak int
lastRow uuid.UUID
}
// observe records the outcome of a pass and returns how many passes in a row
// have failed on different rows. At rowStreakLimit it pauses failure counting
// in the pass, and any pass that does not fail on a row resumes it. A pass that
// failed in the database leaves the state as it was.
func (breaker *rowBreaker) observe(result inbound.MailPassResult, err error) int {
switch {
case err != nil:
case result.Outcome == inbound.MailPassRowFailed:
if result.DeliveryID != breaker.lastRow {
breaker.streak++
}
breaker.lastRow = result.DeliveryID
default:
breaker.streak, breaker.lastRow = 0, uuid.Nil
breaker.pass.PauseFailureCounting(false)
}
if breaker.streak >= rowStreakLimit {
breaker.pass.PauseFailureCounting(true)
}
return breaker.streak
}
// workContext returns a context for the transport call that outlives ctx by
// at most ShutdownGrace. stop releases the watcher goroutine.
func (worker *Worker) workContext(ctx context.Context) (context.Context, func()) {
workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
stopWatching := context.AfterFunc(ctx, func() {
timer := time.NewTimer(worker.settings.ShutdownGrace)
defer timer.Stop()
select {
case <-timer.C:
cancel()
case <-workCtx.Done():
}
})
return workCtx, func() {
stopWatching()
cancel()
}
}
@@ -0,0 +1,306 @@
package mailsender
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/worker/retry"
)
const testWait = 5 * time.Second
type scriptedPass struct {
mu sync.Mutex
steps []step
calls []time.Time
called chan struct{}
workCtx context.Context
paused []bool
}
type step struct {
result inbound.MailPassResult
err error
}
func newScriptedPass(steps ...step) *scriptedPass {
return &scriptedPass{steps: steps, called: make(chan struct{}, 64)}
}
func (pass *scriptedPass) ProcessNext(_, workCtx context.Context) (inbound.MailPassResult, error) {
pass.mu.Lock()
pass.calls = append(pass.calls, time.Now())
pass.workCtx = workCtx
next := step{result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}}
if len(pass.steps) > 0 {
next, pass.steps = pass.steps[0], pass.steps[1:]
}
pass.mu.Unlock()
pass.called <- struct{}{}
return next.result, next.err
}
func (pass *scriptedPass) PauseFailureCounting(paused bool) {
pass.mu.Lock()
defer pass.mu.Unlock()
pass.paused = append(pass.paused, paused)
}
func (pass *scriptedPass) count() int {
pass.mu.Lock()
defer pass.mu.Unlock()
return len(pass.calls)
}
type gauge struct {
mu sync.Mutex
history []bool
cancelled []string
}
func (g *gauge) ObserveMailCancelled(reason string) {
g.mu.Lock()
defer g.mu.Unlock()
g.cancelled = append(g.cancelled, reason)
}
func (g *gauge) SetMailSenderRunning(running bool) {
g.mu.Lock()
defer g.mu.Unlock()
g.history = append(g.history, running)
}
func (g *gauge) values() []bool {
g.mu.Lock()
defer g.mu.Unlock()
return append([]bool(nil), g.history...)
}
func testSettings() Settings {
return Settings{
PollInterval: 20 * time.Millisecond,
Backoff: retry.Backoff{Initial: 40 * time.Millisecond, Max: 80 * time.Millisecond},
ShutdownGrace: 50 * time.Millisecond,
}
}
func newTestWorker(t *testing.T, pass inbound.MailPass, metrics Metrics, settings Settings) *Worker {
t.Helper()
worker, err := New(pass, metrics, slog.New(slog.DiscardHandler), settings)
if err != nil {
t.Fatalf("New() error = %v", err)
}
return worker
}
func runWorker(t *testing.T, worker *Worker) (stop func()) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
stopped := make(chan struct{})
go func() {
defer close(stopped)
worker.Run(ctx)
}()
return func() {
cancel()
select {
case <-stopped:
case <-time.After(testWait):
t.Fatal("Run() did not return after its context ended")
}
}
}
func waitForCalls(t *testing.T, pass *scriptedPass, want int) {
t.Helper()
deadline := time.After(testWait)
for pass.count() < want {
select {
case <-pass.called:
case <-deadline:
t.Fatalf("pass called %d times, want at least %d", pass.count(), want)
}
}
}
func TestNewRejectsUnusableSettings(t *testing.T) {
for name, change := range map[string]func(*Settings){
"no poll interval": func(settings *Settings) { settings.PollInterval = 0 },
"no shutdown grace": func(settings *Settings) { settings.ShutdownGrace = 0 },
"no initial backoff": func(settings *Settings) { settings.Backoff.Initial = 0 },
"maximum below start": func(settings *Settings) {
settings.Backoff = retry.Backoff{Initial: time.Second, Max: time.Millisecond}
},
} {
t.Run(name, func(t *testing.T) {
settings := testSettings()
change(&settings)
if _, err := New(newScriptedPass(), &gauge{}, slog.New(slog.DiscardHandler), settings); err == nil {
t.Fatal("New() accepted unusable settings")
}
})
}
}
func TestRunReportsThatItRunsOnlyWhileTheLoopDoes(t *testing.T) {
metrics := &gauge{}
worker := newTestWorker(t, newScriptedPass(), metrics, testSettings())
if got := metrics.values(); len(got) != 0 {
t.Fatalf("gauge was set before Run: %v", got)
}
stop := runWorker(t, worker)
deadline := time.After(testWait)
for len(metrics.values()) == 0 {
select {
case <-deadline:
t.Fatal("the loop never reported that it runs")
case <-time.After(time.Millisecond):
}
}
if got := metrics.values(); got[0] != true {
t.Fatalf("first gauge value = %v, want true", got[0])
}
stop()
if got := metrics.values(); got[len(got)-1] != false {
t.Fatalf("last gauge value = %v, want false after the loop stopped", got[len(got)-1])
}
}
func TestRunWaitsAfterAnIdlePassAndContinuesAtOnceAfterAHandledDelivery(t *testing.T) {
handled := step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}}
pass := newScriptedPass(handled, handled, handled)
settings := testSettings()
settings.PollInterval = time.Hour // an idle pass would stall the test
stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings))
defer stop()
// Three handled passes run back to back; the fourth is idle and the
// worker then waits for the poll interval.
waitForCalls(t, pass, 4)
time.Sleep(100 * time.Millisecond)
if got := pass.count(); got != 4 {
t.Fatalf("pass called %d times, want 4: an idle pass must wait for the poll interval", got)
}
}
func TestRunBacksOffInsteadOfSpinningWhenNothingCanBeSent(t *testing.T) {
for name, failing := range map[string]step{
"no transport": {result: inbound.MailPassResult{Outcome: inbound.MailPassChannelUnavailable}},
"interrupted call": {result: inbound.MailPassResult{Outcome: inbound.MailPassInterrupted}},
"database failure": {err: errors.New("database unavailable")},
} {
t.Run(name, func(t *testing.T) {
steps := make([]step, 50)
for index := range steps {
steps[index] = failing
}
pass := newScriptedPass(steps...)
stop := runWorker(t, newTestWorker(t, pass, &gauge{}, testSettings()))
time.Sleep(300 * time.Millisecond)
stop()
// The delay starts at 20..40 ms and doubles to 40..80 ms: a loop
// that did not back off would have made hundreds of passes.
if got := pass.count(); got < 3 || got > 15 {
t.Fatalf("pass called %d times in 300 ms, want a few spaced by the backoff", got)
}
pass.mu.Lock()
defer pass.mu.Unlock()
for index := 1; index < len(pass.calls); index++ {
if gap := pass.calls[index].Sub(pass.calls[index-1]); gap < 15*time.Millisecond {
t.Fatalf("passes %d and %d were %s apart, want the backoff between them", index, index+1, gap)
}
}
})
}
}
func TestRunReleasesItsWorkContextWhenItStops(t *testing.T) {
pass := newScriptedPass()
worker := newTestWorker(t, pass, &gauge{}, testSettings())
stop := runWorker(t, worker)
waitForCalls(t, pass, 1)
pass.mu.Lock()
workCtx := pass.workCtx
pass.mu.Unlock()
if workCtx.Err() != nil {
t.Fatal("the work context ended while the loop runs")
}
stop()
// Run returned after its own context ended; the work context is released
// by then, so no goroutine waits for a grace that nobody needs. A send in
// progress at shutdown keeps running for the grace first, which the
// integration tests cover with a real transport.
select {
case <-workCtx.Done():
case <-time.After(testWait):
t.Fatal("the work context was not released when Run returned")
}
}
func TestRunCountsCancelledDeliveriesByReasonAndDoesNotBackOffForARowFailure(t *testing.T) {
metrics := &gauge{}
pass := newScriptedPass(
step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelContentInvalid}},
step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed}},
step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelProcessingFailed}},
)
settings := testSettings()
settings.PollInterval = time.Hour
stop := runWorker(t, newTestWorker(t, pass, metrics, settings))
defer stop()
// The first three passes follow each other at once, because a failing row
// has left the head of the queue; the fourth is idle and waits.
waitForCalls(t, pass, 4)
metrics.mu.Lock()
defer metrics.mu.Unlock()
if len(metrics.cancelled) != 2 || metrics.cancelled[0] != "content_invalid" || metrics.cancelled[1] != "processing_failed" {
t.Fatalf("cancelled reasons = %v, want content_invalid and processing_failed", metrics.cancelled)
}
}
func TestRunPausesFailureCountingWhenFailuresHitRowAfterRowAndResumesAfterASuccess(t *testing.T) {
failed := func() step {
return step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: uuid.New()}}
}
pass := newScriptedPass(failed(), failed(), failed(), failed(), step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}})
settings := testSettings()
settings.PollInterval = time.Hour
stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings))
waitForCalls(t, pass, 6)
stop()
pass.mu.Lock()
defer pass.mu.Unlock()
// Paused from the third different row on, resumed by the success.
var sawPause bool
for _, paused := range pass.paused {
sawPause = sawPause || paused
}
if !sawPause || pass.paused[len(pass.paused)-1] {
t.Fatalf("pause calls = %v, want a pause after three different rows and no pause at the end", pass.paused)
}
}
func TestRunDoesNotPauseWhenTheSameRowFailsAgain(t *testing.T) {
id := uuid.New()
same := step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: id}}
pass := newScriptedPass(same, same, same, same)
settings := testSettings()
settings.PollInterval = time.Hour
stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings))
waitForCalls(t, pass, 5)
stop()
pass.mu.Lock()
defer pass.mu.Unlock()
for _, paused := range pass.paused {
if paused {
t.Fatalf("pause calls = %v; one row failing repeatedly is not a global fault", pass.paused)
}
}
}