package bootstrap import ( "context" "fmt" "log/slog" "time" "github.com/google/uuid" "lincodex/backend/config" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/matching" ) const matchesPoolMaxConns = 4 func newMatchHandler( ctx context.Context, settings config.Config, logger *slog.Logger, keyring *identity.Keyring, ) (*v1.MatchHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("match search is 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.newMatchHandler - derive projection key: %w", err) } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, matchesPoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - 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.newMatchHandler - create view service: %w", err) } service, err := matching.NewService(matching.Dependencies{ Transactor: transactor, Cards: views.ListVisibleCards, Views: searchViews(views), Clock: time.Now, Logger: logger, }) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create service: %w", err) } return v1.NewMatchHandler(service), pool.Close, nil } // searchViews adapts the card view service to the search, which charges and // records the candidates it reveals like card reads. func searchViews(views *candidateview.Service) matching.BeginViews { return func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) { session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID) if err != nil { return nil, err } return session, nil } }