Files

54 lines
1.9 KiB
Go

package bootstrap
import (
"context"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/notification"
)
// startupQuotaReportTimeout bounds the two small reads of the startup quota
// report.
const startupQuotaReportTimeout = 10 * time.Second
// reportMailQuota logs the configured provider account with its current day
// and month usage, and warns when the month has usage under another account
// label of the same provider, which is what a renamed EMAIL_ACCOUNT looks
// like. It runs after the startup migrations and under the same switch, is
// skipped for EMAIL_PROVIDER=disabled, and never stops startup: a failed
// read is logged as a warning.
func reportMailQuota(ctx context.Context, settings config.Config, logger *slog.Logger) {
if !settings.DatabaseMigrateOnStart || settings.DatabaseURL == "" || settings.EmailProvider == config.EmailProviderDisabled {
return
}
warn := func(message string, err error) {
logger.Warn(message, slog.String("error", err.Error()))
}
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
warn("mail quota usage was not reported: invalid provider account", err)
return
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
warn("mail quota usage was not reported: invalid limits", err)
return
}
pool, err := postgres.NewPool(ctx, settings.DatabaseURL)
if err != nil {
warn("mail quota usage was not reported: create pool", err)
return
}
defer pool.Close()
ctx, cancel := context.WithTimeout(ctx, startupQuotaReportTimeout)
defer cancel()
reader := postgres.NewMailQuotaStore(pool).MailQuotas()
if err := notification.ReportQuotaUsage(ctx, reader, account, limits, time.Now(), logger); err != nil {
warn("mail quota usage was not reported", err)
}
}