package bootstrap import ( "context" "fmt" "log/slog" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/config" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/anonymousprofile" "lincodex/backend/internal/usecase/candidateprivacy" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/identity" ) const privacyPoolMaxConns = 4 func newPrivacyHandler( ctx context.Context, settings config.Config, logger *slog.Logger, keyring *identity.Keyring, ) (*v1.PrivacyHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("privacy operations are not served because DATABASE_URL is not set") return nil, func() {}, nil } key, err := keyring.CandidateViewPseudonymKey() if err != nil { return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - derive projection key: %w", err) } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, privacyPoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create pool: %w", err) } transactor := postgres.NewTransactor(pool) views, err := newCandidateViewService(pool, transactor, key) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err) } privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{ Transactor: transactor, Clock: time.Now, Semantic: newSemanticTrigger(settings), }) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create settings service: %w", err) } return v1.NewPrivacyHandler(views, privacy, settings.AppPublicURL), pool.Close, nil } // newCandidateViewService builds the organization card checks on the given // pool. The privacy handler and the evidence handler each own a pool and a // service, so their connection use stays separate. func newCandidateViewService( pool *pgxpool.Pool, transactor *postgres.Transactor, key domain.CandidateViewPseudonymKey, ) (*candidateview.Service, error) { projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now) quota := companyquota.NewService(time.Now) return candidateview.NewService(candidateview.Dependencies{ Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveCardView(ctx, unit, organization, candidateID) }, }) }