188 lines
7.1 KiB
Go
188 lines
7.1 KiB
Go
// 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()
|
|
}
|
|
}
|