516 lines
19 KiB
Go
516 lines
19 KiB
Go
// Package candidateview applies current publication, membership, hidden-
|
|
// organization, cohort, and quota rules to anonymous candidate reads.
|
|
package candidateview
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
var (
|
|
ErrForbidden = errors.New("candidate view is forbidden")
|
|
ErrCandidateCardNotFound = errors.New("candidate card not found")
|
|
ErrInvalidCandidateHandle = errors.New("candidate handle is invalid")
|
|
ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read")
|
|
ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable")
|
|
ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted")
|
|
)
|
|
|
|
const maxCohortStabilizationPasses = 8
|
|
|
|
// Projector builds the shared, strict anonymous-card projection.
|
|
type Projector interface {
|
|
ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error)
|
|
PreviewSource(source domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error)
|
|
}
|
|
|
|
// CardViewQuota reserves the current policy's distinct card-view allowance.
|
|
// Bootstrap adapts the shared company-quota usecase without making this
|
|
// read-policy package depend on another usecase package.
|
|
type CardViewQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
|
|
|
// Dependencies configure the stateless candidate-view policy service.
|
|
type Dependencies struct {
|
|
Transactor outbound.Transactor
|
|
Projector Projector
|
|
PseudonymKey domain.CandidateViewPseudonymKey
|
|
Quota CardViewQuota
|
|
Clock func() time.Time
|
|
}
|
|
|
|
// Service rechecks private visibility state in a transaction for each read.
|
|
type Service struct {
|
|
transactor outbound.Transactor
|
|
projector Projector
|
|
pseudonymKey domain.CandidateViewPseudonymKey
|
|
quota CardViewQuota
|
|
clock func() time.Time
|
|
}
|
|
|
|
func NewService(deps Dependencies) (*Service, error) {
|
|
if deps.Transactor == nil || deps.Projector == nil || deps.Quota == nil || deps.Clock == nil {
|
|
return nil, fmt.Errorf("candidateview.NewService - dependencies are missing: %w", ErrCandidateViewServiceMissing)
|
|
}
|
|
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
|
|
return nil, fmt.Errorf("candidateview.NewService - pseudonym key is invalid: %w", ErrCandidateViewServiceMissing)
|
|
}
|
|
return &Service{
|
|
transactor: deps.Transactor, projector: deps.Projector, pseudonymKey: deps.PseudonymKey, quota: deps.Quota,
|
|
clock: deps.Clock,
|
|
}, nil
|
|
}
|
|
|
|
// RateLimitedError carries only the retry time derived from the current
|
|
// organization quota; it does not include candidate or organization values.
|
|
type RateLimitedError struct{ RetryAt time.Time }
|
|
|
|
func (err *RateLimitedError) Error() string { return ErrCandidateViewQuotaExceeded.Error() }
|
|
func (err *RateLimitedError) Unwrap() error { return ErrCandidateViewQuotaExceeded }
|
|
|
|
// GetOrganizationCard reads a handle only from the current, locked,
|
|
// organization-visible cohort. Quota and the field-code audit commit with the
|
|
// visibility checks, so failed reads leave neither behind.
|
|
func (service *Service) GetOrganizationCard(
|
|
ctx context.Context,
|
|
actorID, organizationID uuid.UUID,
|
|
handle string,
|
|
) (domain.AnonymousCandidateViewDTO, error) {
|
|
const location = "candidateview.Service.GetOrganizationCard"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return domain.AnonymousCandidateViewDTO{}, ErrForbidden
|
|
}
|
|
if !domain.IsCandidateViewPseudonym(handle) {
|
|
return domain.AnonymousCandidateViewDTO{}, ErrInvalidCandidateHandle
|
|
}
|
|
var result domain.AnonymousCandidateViewDTO
|
|
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
view, err := service.getOrganizationCardInTransaction(ctx, unit, actorID, organizationID, handle, location)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result = view
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (service *Service) getOrganizationCardInTransaction(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
handle, location string,
|
|
) (domain.AnonymousCandidateViewDTO, error) {
|
|
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, err
|
|
}
|
|
decision, err := service.quota(ctx, unit, organization, candidateID)
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - reserve card view: %w", location, err)
|
|
}
|
|
if !decision.Allowed {
|
|
return domain.AnonymousCandidateViewDTO{}, &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
|
}
|
|
event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, service.clock())
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build access audit: %w", location, err)
|
|
}
|
|
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - record access audit: %w", location, err)
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
func (service *Service) currentOrganizationCard(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
handle, location string,
|
|
) (domain.Organization, outbound.PrivacyViewRepository, uuid.UUID, domain.AnonymousCandidateViewDTO, error) {
|
|
organization, repository, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
|
}
|
|
candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
|
}
|
|
view, err := projectedViewForHandle(service, organizationID, sources, handle, location)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
|
}
|
|
return organization, repository, candidateID, view, nil
|
|
}
|
|
|
|
func loadCurrentVisibleCohort(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
location string,
|
|
) (domain.Organization, outbound.PrivacyViewRepository, []domain.CandidateViewSource, error) {
|
|
organization, err := authorizeEmployer(ctx, unit, actorID, organizationID)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, nil, err
|
|
}
|
|
repository, err := privacyViewRepository(unit)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, nil, err
|
|
}
|
|
sources, err := repository.ListVisibleCandidateViewSources(ctx, organizationID)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, nil, fmt.Errorf("%s - read candidate cohort: %w", location, err)
|
|
}
|
|
sources, err = lockCurrentVisibleCohort(ctx, unit, repository, organizationID, sources)
|
|
if err != nil {
|
|
return domain.Organization{}, nil, nil, err
|
|
}
|
|
return organization, repository, sources, nil
|
|
}
|
|
|
|
func candidateIDForHandle(
|
|
service *Service,
|
|
organizationID uuid.UUID,
|
|
sources []domain.CandidateViewSource,
|
|
handle, location string,
|
|
) (uuid.UUID, error) {
|
|
for _, source := range sources {
|
|
alias, err := service.sourceAlias(organizationID, source)
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("%s - derive current alias: %w", location, err)
|
|
}
|
|
if alias == handle {
|
|
return source.CandidateID(), nil
|
|
}
|
|
}
|
|
return uuid.Nil, ErrCandidateCardNotFound
|
|
}
|
|
|
|
func projectedViewForHandle(
|
|
service *Service,
|
|
organizationID uuid.UUID,
|
|
sources []domain.CandidateViewSource,
|
|
handle, location string,
|
|
) (domain.AnonymousCandidateViewDTO, error) {
|
|
views, err := service.projector.ProjectSources(organizationID, sources)
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build current candidate view: %w", location, err)
|
|
}
|
|
for _, view := range views {
|
|
if view.Pseudonym == handle {
|
|
return view, nil
|
|
}
|
|
}
|
|
return domain.AnonymousCandidateViewDTO{}, ErrCandidateCardNotFound
|
|
}
|
|
|
|
// PreviewResult contains only the candidate's own current publication state
|
|
// and the strict anonymous-card projection.
|
|
type PreviewResult struct {
|
|
Published bool
|
|
Fields domain.CardFieldSet
|
|
Card *domain.AnonymousCandidateViewDTO
|
|
GeneratedAt time.Time
|
|
}
|
|
|
|
// GetMyCardPreview computes a private preview without organization cohort
|
|
// context, employer quota, or access history.
|
|
func (service *Service) GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (PreviewResult, error) {
|
|
const location = "candidateview.Service.GetMyCardPreview"
|
|
if actorID == uuid.Nil {
|
|
return PreviewResult{}, ErrForbidden
|
|
}
|
|
var result PreviewResult
|
|
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
|
|
return err
|
|
}
|
|
repository, err := privacyViewRepository(unit)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
generatedAt := service.clock().UTC().Truncate(time.Microsecond)
|
|
if generatedAt.IsZero() {
|
|
return fmt.Errorf("%s - clock returned zero: %w", location, ErrCandidateViewServiceMissing)
|
|
}
|
|
_, consentErr := repository.LockCurrentC2ForView(ctx, actorID)
|
|
if errors.Is(consentErr, outbound.ErrCandidateC2Unavailable) {
|
|
result = PreviewResult{GeneratedAt: generatedAt}
|
|
return nil
|
|
}
|
|
if consentErr != nil {
|
|
return fmt.Errorf("%s - lock current C2: %w", location, consentErr)
|
|
}
|
|
published, err := repository.LockPublicationForPreview(ctx, actorID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - lock publication: %w", location, err)
|
|
}
|
|
if !published {
|
|
result = PreviewResult{GeneratedAt: generatedAt}
|
|
return nil
|
|
}
|
|
source, err := repository.ReadCandidateViewSourceForPreview(ctx, actorID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read private preview source: %w", location, err)
|
|
}
|
|
card, err := service.projector.PreviewSource(source)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build private preview: %w", location, err)
|
|
}
|
|
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, GeneratedAt: generatedAt}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return PreviewResult{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// ListMyCardAccessHistory returns one owner-scoped history page.
|
|
func (service *Service) ListMyCardAccessHistory(
|
|
ctx context.Context,
|
|
command outbound.CandidateCardAccessListQuery,
|
|
) (outbound.CandidateCardAccessListPage, error) {
|
|
const location = "candidateview.Service.ListMyCardAccessHistory"
|
|
if command.CandidateID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxCandidateCardAccessPageSize {
|
|
return outbound.CandidateCardAccessListPage{}, domain.ErrInvalidCandidateCardAccess
|
|
}
|
|
var result outbound.CandidateCardAccessListPage
|
|
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := authorizeCandidate(ctx, unit, command.CandidateID); err != nil {
|
|
return err
|
|
}
|
|
repository, err := privacyViewRepository(unit)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result, err = repository.ListCandidateCardAccess(ctx, command)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read owner access history: %w", location, err)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// CurrentContactFields returns only the current allowlisted grant fields.
|
|
// The production repository is closed until invitation grants are persisted.
|
|
// No workflow state or C4 ledger entry alone can open this read.
|
|
func (service *Service) CurrentContactFields(
|
|
ctx context.Context,
|
|
actorID, organizationID uuid.UUID,
|
|
handle string,
|
|
) (domain.ContactFieldSet, error) {
|
|
const location = "candidateview.Service.CurrentContactFields"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return domain.ContactFieldSet{}, ErrForbidden
|
|
}
|
|
if !domain.IsCandidateViewPseudonym(handle) {
|
|
return domain.ContactFieldSet{}, ErrInvalidCandidateHandle
|
|
}
|
|
var fields domain.ContactFieldSet
|
|
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
_, repository, candidateID, _, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fields, err = repository.CurrentFields(ctx, organizationID, candidateID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read current contact grant: %w", location, err)
|
|
}
|
|
if fields.IsZero() {
|
|
return outbound.ErrContactAccessClosed
|
|
}
|
|
event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
|
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
|
Kind: domain.CandidateCardAccessContactRead, ContactFields: fields.Fields(), OccurredAt: service.clock(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build contact access audit: %w", location, err)
|
|
}
|
|
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
|
return fmt.Errorf("%s - record contact access audit: %w", location, err)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.ContactFieldSet{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
|
}
|
|
return fields, nil
|
|
}
|
|
|
|
func authorizeEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (domain.Organization, error) {
|
|
user, err := unit.Users().GetByID(ctx, actorID)
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
return domain.Organization{}, ErrForbidden
|
|
}
|
|
if err != nil {
|
|
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read actor account: %w", err)
|
|
}
|
|
if !user.EmailVerified() || user.Scenario != domain.ScenarioEmployer {
|
|
return domain.Organization{}, ErrForbidden
|
|
}
|
|
if _, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID); err != nil {
|
|
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
|
return domain.Organization{}, outbound.ErrOrganizationNotFound
|
|
}
|
|
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - lock membership: %w", err)
|
|
}
|
|
organization, _, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
|
|
if err != nil {
|
|
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read organization: %w", err)
|
|
}
|
|
return organization, nil
|
|
}
|
|
|
|
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
|
|
user, err := unit.Users().GetByID(ctx, actorID)
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
return ErrForbidden
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("candidateview.authorizeCandidate - read actor account: %w", err)
|
|
}
|
|
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
|
|
return ErrForbidden
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func privacyViewRepository(unit outbound.UnitOfWork) (outbound.PrivacyViewRepository, error) {
|
|
repository := unit.PrivacyView()
|
|
if repository == nil {
|
|
return nil, ErrCandidateViewServiceMissing
|
|
}
|
|
return repository, nil
|
|
}
|
|
|
|
func lockCurrentVisibleCohort(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
repository outbound.PrivacyViewRepository,
|
|
organizationID uuid.UUID,
|
|
sources []domain.CandidateViewSource,
|
|
) ([]domain.CandidateViewSource, error) {
|
|
checked := make(map[uuid.UUID]bool)
|
|
current := sources
|
|
for range maxCohortStabilizationPasses {
|
|
for _, source := range current {
|
|
candidateID := source.CandidateID()
|
|
if _, exists := checked[candidateID]; exists {
|
|
continue
|
|
}
|
|
visible, err := lockCandidateVisibility(ctx, unit, repository, organizationID, candidateID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
checked[candidateID] = visible
|
|
}
|
|
refreshed, err := repository.ListVisibleCandidateViewSources(ctx, organizationID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("candidateview.lockCurrentVisibleCohort - re-read cohort: %w", err)
|
|
}
|
|
allLocked := true
|
|
for _, source := range refreshed {
|
|
eligible, exists := checked[source.CandidateID()]
|
|
if !exists {
|
|
allLocked = false
|
|
break
|
|
}
|
|
if !eligible {
|
|
return nil, ErrConcurrentVisibilityChange
|
|
}
|
|
}
|
|
if allLocked {
|
|
return refreshed, nil
|
|
}
|
|
current = refreshed
|
|
}
|
|
return nil, ErrConcurrentVisibilityChange
|
|
}
|
|
|
|
func lockCandidateVisibility(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
repository outbound.PrivacyViewRepository,
|
|
organizationID, candidateID uuid.UUID,
|
|
) (bool, error) {
|
|
if err := repository.LockCandidateAccountForView(ctx, candidateID); err != nil {
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
candidate, err := unit.Users().GetByID(ctx, candidateID)
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
return false, nil
|
|
}
|
|
return false, fmt.Errorf("candidateview.lockCandidateVisibility - read candidate account: %w", err)
|
|
}
|
|
if !candidate.EmailVerified() || candidate.Scenario != domain.ScenarioCandidate {
|
|
return false, nil
|
|
}
|
|
consentID, err := repository.LockCurrentC2ForView(ctx, candidateID)
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrCandidateC2Unavailable) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
return repository.LockVisiblePublicationForView(ctx, organizationID, candidateID, consentID)
|
|
}
|
|
|
|
func (service *Service) sourceAlias(organizationID uuid.UUID, source domain.CandidateViewSource) (string, error) {
|
|
alias, err := service.pseudonymKey.ForOrganization(organizationID, source.CandidateID())
|
|
if err != nil {
|
|
return "", fmt.Errorf("candidateview.Service.sourceAlias - derive candidate alias: %w", domain.ErrInvalidAnonymousCandidateView)
|
|
}
|
|
return alias, nil
|
|
}
|
|
|
|
func cardViewAccessEvent(
|
|
candidateID, organizationID, actorID uuid.UUID,
|
|
view domain.AnonymousCandidateViewDTO,
|
|
at time.Time,
|
|
) (domain.CandidateCardAccess, error) {
|
|
var fields []domain.CardField
|
|
if len(view.Categories) > 0 {
|
|
fields = append(fields, domain.CardFieldCategories)
|
|
}
|
|
if len(view.Skills) > 0 {
|
|
fields = append(fields, domain.CardFieldStack)
|
|
}
|
|
if view.ExperienceBand != nil {
|
|
fields = append(fields, domain.CardFieldExperience)
|
|
}
|
|
if len(view.SelfAssessment) > 0 {
|
|
fields = append(fields, domain.CardFieldSelfAssessment)
|
|
}
|
|
if len(view.WorkFormats) > 0 {
|
|
fields = append(fields, domain.CardFieldWorkFormats)
|
|
}
|
|
if view.SalaryCompatibility != nil {
|
|
fields = append(fields, domain.CardFieldSalaryCompatibility)
|
|
}
|
|
if !domain.IsCandidateViewPseudonym(view.Pseudonym) {
|
|
return domain.CandidateCardAccess{}, ErrInvalidCandidateHandle
|
|
}
|
|
return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
|
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
|
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: at,
|
|
})
|
|
}
|