feat(notifications): send product notifications with a rights check right before each send

This commit is contained in:
shira committed 2026-10-09 20:38:39 +03:00
1 parent a856066316
commit 623d41b969
59 files changed
+4125 -1126

No files matched your search

+19 -10
View File
@@ -51,6 +51,10 @@ type Application struct {
// the servers run. It is nil with EMAIL_PROVIDER=disabled or when the
// database is not configured.
mailSending *mailsender.Worker
// notificationSending sends the stored product notifications while the
// servers run, after their rights checks. It is nil under the same
// conditions as mailSending.
notificationSending *notificationSendingWorker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
@@ -66,19 +70,21 @@ func NewApplication(
consumers eventConsumers,
jobs *jobrunner.Worker,
mailSending *mailsender.Worker,
notificationSending *notificationSendingWorker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
deliveryMetrics: deliveryMetrics,
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
notificationSending: notificationSending,
deliveryMetrics: deliveryMetrics,
}
}
@@ -224,6 +230,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.mailSending != nil {
workers.Go(func() { application.mailSending.Run(ctx) })
}
if application.notificationSending != nil {
workers.Go(func() { application.notificationSending.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
+1 -1
View File
@@ -207,7 +207,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, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, 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, nil, sampler)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -93,7 +93,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, nil)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+27 -15
View File
@@ -105,16 +105,7 @@ func newMailSenderWorker(
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},
},
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
)
@@ -122,11 +113,7 @@ func newMailSenderWorker(
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,
})
worker, err := mailsender.New(sender, metrics, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create worker: %w", err)
@@ -136,6 +123,31 @@ func newMailSenderWorker(
return worker, pool.Close, nil
}
// deliverySenderSettings are the limits of a sending worker of any lane. The
// disabled transport is the only one whose unsent deliveries may be rebound to
// the configured account, so every lane rebinds from it.
func deliverySenderSettings(settings config.Config, account domain.MailProviderAccount) notification.DeliverySenderSettings {
return notification.DeliverySenderSettings{
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},
}
}
// mailSenderLoopSettings are the pacing limits of a sending loop of any lane.
func mailSenderLoopSettings() mailsender.Settings {
return mailsender.Settings{
PollInterval: mailSenderPollInterval,
Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax},
ShutdownGrace: mailSenderShutdownGrace,
}
}
// 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.
@@ -93,7 +93,7 @@ func TestApplicationRunsAndStopsTheMailSenderWorker(t *testing.T) {
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)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
@@ -0,0 +1,107 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"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"
)
// notificationSendingWorker is the sending loop of product notifications. Its
// own type keeps it apart from the service mail loop in the dependency graph.
type notificationSendingWorker struct {
*mailsender.Worker
}
var _ mailsender.Metrics = notificationSenderMetrics{}
// notificationSenderMetrics reports the product loop to the process metrics:
// its running state to its own gauge, and its cancellations to the counter the
// service loop also uses, by reason.
type notificationSenderMetrics struct {
metrics *prometheus.Metrics
}
func (metrics notificationSenderMetrics) SetMailSenderRunning(running bool) {
metrics.metrics.SetNotificationSenderRunning(running)
}
func (metrics notificationSenderMetrics) ObserveMailCancelled(reason string) {
metrics.metrics.ObserveMailCancelled(reason)
}
// newNotificationSenderWorker builds the sending loop of product notifications
// and the PostgreSQL pool it owns. It shares the transport, the provider
// account, and the timing of the service loop, but its quota gate keeps the
// service reserve free: a notification is admitted only while each window stays
// above EMAIL_SERVICE_RESERVE_DAILY and EMAIL_SERVICE_RESERVE_MONTHLY after it.
//
// Like the service loop, it returns no worker when EMAIL_PROVIDER=disabled or
// DATABASE_URL is unset, so a notification waits, pinned to the transport it
// was created under, until a transport runs. Nothing connects here.
func newNotificationSenderWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
mailSender outbound.MailSender,
) (*notificationSendingWorker, func(), error) {
switch {
case settings.EmailProvider == config.EmailProviderDisabled:
logger.Info("notification sender worker is not started because EMAIL_PROVIDER is disabled; stored notifications wait")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("notification 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.newNotificationSenderWorker - provider account: %w", err)
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - quota limits: %w", err)
}
workerLogger := logger.With(slog.String("component", "notification_sender"))
gate, err := notification.NewQuotaGate(account, limits, mailIdempotencyWindow(settings), time.Now, workerLogger).
WithReserve(int64(settings.EmailServiceReserveDaily), int64(settings.EmailServiceReserveMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - service reserve: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, mailSenderPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create pool: %w", err)
}
sender, err := notification.NewNotificationSender(
postgres.NewTransactor(pool),
mailSender,
gate,
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
// Every subject kind a notification may name needs its check here. A
// kind without one is refused by the sender, so it never goes out
// unchecked.
[]notification.SubjectRights{notification.NewInvitationNoticeRights()},
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create sender: %w", err)
}
worker, err := mailsender.New(sender, notificationSenderMetrics{metrics: metrics}, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create worker: %w", err)
}
// The application stops the worker before this cleanup runs, so no send
// uses the pool while it closes.
return &notificationSendingWorker{Worker: worker}, pool.Close, nil
}
@@ -0,0 +1,93 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
func TestNewNotificationSenderWorkerSkipsWithoutWork(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 := newNotificationSenderWorker(t.Context(), test.settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("newNotificationSenderWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
// The product loop has its own gauge: without it the gauge reads 0,
// and the service loop's gauge is untouched.
body := scrape(metrics)
if !strings.Contains(body, "lincodex_notification_sender_running 0\n") {
t.Fatalf("metrics lack lincodex_notification_sender_running 0:\n%s", body)
}
})
}
}
func TestApplicationRunsAndStopsTheNotificationSenderWorker(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 := newNotificationSenderWorker(t.Context(), settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("newNotificationSenderWorker() built no worker for an active transport")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, 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_notification_sender_running 1\n") {
if time.Now().After(deadline) {
t.Fatal("the product 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_notification_sender_running 0\n") {
t.Fatalf("the gauge did not return to 0 after the loop stopped:\n%s", body)
}
}
+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, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -67,6 +67,7 @@ func initialize(
newEventConsumers,
newJobWorker,
newMailSenderWorker,
newNotificationSenderWorker,
newDeliveryMetrics,
NewApplication,
),
+30 -2
View File
@@ -381,7 +381,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup23, err := newDeliveryMetrics(ctx, config2, logger, metrics)
bootstrapNotificationSendingWorker, cleanup23, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup22()
cleanup21()
@@ -407,8 +407,36 @@ 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, mailsenderWorker, sampler)
sampler, cleanup24, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup23()
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, bootstrapNotificationSendingWorker, sampler)
return application, func() {
cleanup24()
cleanup23()
cleanup22()
cleanup21()