777 lines
30 KiB
Go
777 lines
30 KiB
Go
// Package candidateview applies current publication, membership, hidden-
|
|
// organization, cohort, and quota rules to anonymous candidate reads.
|
|
package candidateview
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"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 = outbound.ErrConcurrentVisibilityChange
|
|
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 {
|
|
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
|
|
return err
|
|
}
|
|
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
|
|
}
|
|
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
|
return cardViewAccessEvent(candidateID, organizationID, actorID, view, at)
|
|
})
|
|
if err != nil {
|
|
return domain.AnonymousCandidateViewDTO{}, err
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
// reserveCardView consumes the card-view quota and appends the access audit
|
|
// that auditFor builds. Both commit with the visibility checks that the
|
|
// caller ran in the same transaction, so a failed read leaves neither behind.
|
|
func (service *Service) reserveCardView(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
repository outbound.PrivacyViewRepository,
|
|
organization domain.Organization,
|
|
candidateID uuid.UUID,
|
|
location string,
|
|
auditFor func(at time.Time) (domain.CandidateCardAccess, error),
|
|
) error {
|
|
decision, err := service.quota(ctx, unit, organization, candidateID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - reserve card view: %w", location, err)
|
|
}
|
|
if !decision.Allowed {
|
|
return &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
|
}
|
|
event, err := auditFor(service.clock())
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build access audit: %w", location, err)
|
|
}
|
|
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
|
return fmt.Errorf("%s - record access audit: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListVisibleCards returns the cards of the current, locked,
|
|
// organization-visible cohort, built by the same projection as a card read, so
|
|
// a handle in the list is a handle that GetOrganizationCard opens. It runs the
|
|
// membership, effective C2 publication, hiding, and minimum-cohort checks of a
|
|
// card read under the same locks, inside the caller's transaction. A candidate
|
|
// whose card is suppressed by the cohort rules is not in the list.
|
|
//
|
|
// Listing itself consumes nothing. The caller charges and records each
|
|
// candidate that it reveals through BeginSearchViews, because an entry holds
|
|
// card content.
|
|
func (service *Service) ListVisibleCards(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
) ([]domain.VisibleCandidateCard, error) {
|
|
const location = "candidateview.Service.ListVisibleCards"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return nil, ErrForbidden
|
|
}
|
|
_, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
candidateByAlias := make(map[string]uuid.UUID, len(sources))
|
|
for _, source := range sources {
|
|
alias, err := service.sourceAlias(organizationID, source)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - derive current alias: %w", location, err)
|
|
}
|
|
candidateByAlias[alias] = source.CandidateID()
|
|
}
|
|
views, err := service.projector.ProjectSources(organizationID, sources)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - build current candidate views: %w", location, err)
|
|
}
|
|
cards := make([]domain.VisibleCandidateCard, 0, len(views))
|
|
for _, view := range views {
|
|
candidateID, exists := candidateByAlias[view.Pseudonym]
|
|
if !exists {
|
|
return nil, fmt.Errorf("%s - projected view has no source: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
|
}
|
|
cards = append(cards, domain.VisibleCandidateCard{CandidateID: candidateID, Card: view})
|
|
}
|
|
return cards, nil
|
|
}
|
|
|
|
// SearchViews charges and records the candidates that one search reveals. It is
|
|
// bound to the caller's transaction and to the organization that was already
|
|
// authorized, so a failure of the search leaves neither a charge nor a record.
|
|
type SearchViews struct {
|
|
service *Service
|
|
unit outbound.UnitOfWork
|
|
organization domain.Organization
|
|
repository outbound.PrivacyViewRepository
|
|
actorID uuid.UUID
|
|
}
|
|
|
|
// BeginSearchViews prepares the charging of a search inside the caller's
|
|
// transaction. The actor must have an active membership of the organization.
|
|
func (service *Service) BeginSearchViews(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
) (*SearchViews, error) {
|
|
const location = "candidateview.Service.BeginSearchViews"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return nil, ErrForbidden
|
|
}
|
|
organization, err := authorizeEmployer(ctx, unit, actorID, organizationID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
repository, err := privacyViewRepository(unit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - open the access repository: %w", location, err)
|
|
}
|
|
return &SearchViews{service: service, unit: unit, organization: organization, repository: repository, actorID: actorID}, nil
|
|
}
|
|
|
|
// Reserve counts the candidate as a distinct card view of the organization. A
|
|
// candidate that the organization already viewed inside the window is allowed
|
|
// again without another charge. It reports false, writing nothing, when the
|
|
// allowance is used up.
|
|
func (views *SearchViews) Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error) {
|
|
decision, err := views.service.quota(ctx, views.unit, views.organization, candidateID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("candidateview.SearchViews.Reserve - reserve card view: %w", err)
|
|
}
|
|
return decision.Allowed, nil
|
|
}
|
|
|
|
// Record appends the access history entry for the fields that a search
|
|
// actually returned about the candidate, so the candidate sees the read.
|
|
func (views *SearchViews) Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error {
|
|
const location = "candidateview.SearchViews.Record"
|
|
event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
|
CandidateID: candidateID, OrganizationID: views.organization.ID(), ActorID: views.actorID,
|
|
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: views.service.clock(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build access audit: %w", location, err)
|
|
}
|
|
if err := views.repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
|
return fmt.Errorf("%s - record access audit: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AuthorizeCategoriesSection runs the checks of an organization card read
|
|
// inside the caller's transaction and reports which candidate, and which
|
|
// categories (specialization and grade), the card shows. It exists for the sections
|
|
// of a card that explain its categories, such as the permitted evidence: they
|
|
// must not disclose more than the categories of the current card do.
|
|
//
|
|
// The checks are those of GetOrganizationCard: the active membership of the
|
|
// actor, the effective C2 publication, the hiding of this organization, and
|
|
// the minimum cohort, all under the same locks. The card must also show at
|
|
// least one category after the cohort rules, otherwise the answer is
|
|
// ErrCandidateCardNotFound, the same as for an unknown handle. A successful
|
|
// call consumes the card-view quota and records the access with the
|
|
// categories field, so the candidate sees the read in the access history. The
|
|
// caller reads the section in the same transaction, after this returns.
|
|
func (service *Service) AuthorizeCategoriesSection(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
handle string,
|
|
) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
|
const location = "candidateview.Service.AuthorizeCategoriesSection"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return uuid.Nil, nil, ErrForbidden
|
|
}
|
|
if !domain.IsCandidateViewPseudonym(handle) {
|
|
return uuid.Nil, nil, ErrInvalidCandidateHandle
|
|
}
|
|
// The caller's transaction has taken no share lock of the organization yet.
|
|
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
|
|
return uuid.Nil, nil, err
|
|
}
|
|
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
|
if err != nil {
|
|
return uuid.Nil, nil, err
|
|
}
|
|
if len(view.Categories) == 0 {
|
|
return uuid.Nil, nil, ErrCandidateCardNotFound
|
|
}
|
|
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
|
return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
|
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
|
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories}, OccurredAt: at,
|
|
})
|
|
})
|
|
if err != nil {
|
|
return uuid.Nil, nil, err
|
|
}
|
|
return candidateID, slices.Clone(view.Categories), nil
|
|
}
|
|
|
|
// ResolveCandidateHandle turns the handle of a card of this organization into
|
|
// the candidate it stands for, inside the caller's transaction. It applies the
|
|
// checks of a card read under the same locks: the active membership of the
|
|
// actor, the effective C2 publication, the hiding of this organization, and
|
|
// the minimum cohort, so a handle of another organization, an unknown handle,
|
|
// a candidate who revoked the publication or hid the profile from the
|
|
// organization, and a card that the cohort rules suppress all answer
|
|
// ErrCandidateCardNotFound. The caller cannot tell the cases apart.
|
|
//
|
|
// It consumes no card-view quota and writes no access history: it returns an
|
|
// identifier for the server's own use and shows no card content, and the
|
|
// search or the card read that produced the handle was charged when it
|
|
// revealed the candidate. The identifier must never leave the server.
|
|
//
|
|
// The caller's transaction must not hold a share lock of the organization yet,
|
|
// so that the exclusive organization lock of the quota writers is taken first.
|
|
func (service *Service) ResolveCandidateHandle(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
actorID, organizationID uuid.UUID,
|
|
handle string,
|
|
) (uuid.UUID, error) {
|
|
const location = "candidateview.Service.ResolveCandidateHandle"
|
|
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
|
return uuid.Nil, ErrForbidden
|
|
}
|
|
if !domain.IsCandidateViewPseudonym(handle) {
|
|
return uuid.Nil, ErrInvalidCandidateHandle
|
|
}
|
|
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
_, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location)
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
// A card that the cohort rules suppress is not offered by a search, so its
|
|
// handle is not accepted either.
|
|
if _, err := projectedViewForHandle(service, organizationID, sources, handle, location); err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
return candidateID, 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
|
|
// Evidence is what an organization would read with the categories of the
|
|
// card: for each category, the one fact that supports its confirmed grade.
|
|
// It is empty when the card shows no category.
|
|
Evidence []domain.EvidenceOrganizationFact
|
|
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)
|
|
}
|
|
var facts []domain.EvidenceOrganizationFact
|
|
if len(card.Categories) > 0 {
|
|
if facts, err = unit.Evidence().ListPreviewFacts(ctx, actorID, card.Categories); err != nil {
|
|
return fmt.Errorf("%s - read preview evidence: %w", location, err)
|
|
}
|
|
}
|
|
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, Evidence: facts, 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
|
|
}
|
|
|
|
// lockOrganizationFirst takes the exclusive organization lock that the card-view
|
|
// reservation takes later. The membership check holds only a share lock on the
|
|
// same row, and two readers of one organization that each hold a share lock
|
|
// and then ask for the exclusive one deadlock. Taking the exclusive lock before
|
|
// any share lock follows the documented lock order and serializes the charges
|
|
// of one organization.
|
|
func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID) error {
|
|
repository := unit.CompanyQuotas()
|
|
if repository == nil {
|
|
return fmt.Errorf("candidateview.lockOrganizationFirst - quota repository is missing: %w", ErrCandidateViewServiceMissing)
|
|
}
|
|
if err := repository.LockOrganization(ctx, organizationID); err != nil {
|
|
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
|
|
return outbound.ErrOrganizationNotFound
|
|
}
|
|
return fmt.Errorf("candidateview.lockOrganizationFirst - lock organization: %w", err)
|
|
}
|
|
return 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,
|
|
})
|
|
}
|