155 lines
6.9 KiB
Go
155 lines
6.9 KiB
Go
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
|
|
}
|