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 ¬ificationSendingWorker{Worker: worker}, pool.Close, nil }