feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

@@ -174,6 +174,16 @@ func (unit contactAccessUnit) Organizations() outbound.OrganizationRepository {
return unit.organizations
}
func (unit contactAccessUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view }
func (unit contactAccessUnit) CompanyQuotas() outbound.CompanyQuotaRepository {
return organizationLockStub{}
}
// organizationLockStub accepts the organization lock and is not used for more.
type organizationLockStub struct {
outbound.CompanyQuotaRepository
}
func (organizationLockStub) LockOrganization(context.Context, uuid.UUID) error { return nil }
type contactAccessUsers struct {
outbound.UserRepository
@@ -19,7 +19,7 @@ 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")
ErrConcurrentVisibilityChange = outbound.ErrConcurrentVisibilityChange
ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable")
ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted")
)
@@ -92,6 +92,9 @@ func (service *Service) GetOrganizationCard(
}
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
@@ -153,6 +156,114 @@ func (service *Service) reserveCardView(
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
@@ -180,6 +291,10 @@ func (service *Service) AuthorizeCategoriesSection(
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
@@ -429,6 +544,26 @@ func (service *Service) CurrentContactFields(
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) {
@@ -0,0 +1,108 @@
package candidateview
import (
"context"
"errors"
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (fixture *categoriesSectionFixture) listVisible(t *testing.T) ([]domain.VisibleCandidateCard, error) {
t.Helper()
var cards []domain.VisibleCandidateCard
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
cards, err = fixture.service.ListVisibleCards(ctx, unit, fixture.actorID, fixture.organizationID)
return err
})
return cards, err
}
func TestListVisibleCardsReturnsTheCardsOfTheCurrentCohortWithoutAViewTrace(t *testing.T) {
t.Parallel()
shown := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}}
fixture := newCategoriesSectionFixture(t, shown, true, domain.ScenarioEmployer)
cards, err := fixture.listVisible(t)
if err != nil {
t.Fatalf("ListVisibleCards() error = %v", err)
}
if len(cards) != 1 || cards[0].CandidateID == uuid.Nil || cards[0].Card.Pseudonym != fixture.handle ||
!slices.Equal(cards[0].Card.Categories, shown) {
t.Fatalf("cards = %v, want the one visible card under the organization handle", cards)
}
if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 {
t.Fatalf("quota calls = %d, audits = %v, want a listing that is not a card view", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestListVisibleCardsRefusesAnActorWithoutAnEmployerRole(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate)
if _, err := fixture.listVisible(t); !errors.Is(err, ErrForbidden) {
t.Fatalf("ListVisibleCards() error = %v, want ErrForbidden", err)
}
if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 {
t.Fatalf("quota calls = %d, audits = %v, want no trace", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestSearchViewsChargeAndRecordWhatTheSearchReveals(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioEmployer)
candidateID := uuid.New()
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID)
if err != nil {
return err
}
allowed, err := views.Reserve(ctx, candidateID)
if err != nil || !allowed {
t.Fatalf("Reserve() = %v, %v, want allowed", allowed, err)
}
return views.Record(ctx, candidateID, []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack})
})
if err != nil {
t.Fatalf("search views error = %v", err)
}
if fixture.quotaCalls != 1 || len(fixture.contact.audits) != 1 || fixture.contact.audits[0].Kind() != domain.CandidateCardAccessCardViewed ||
!slices.Equal(fixture.contact.audits[0].FieldCodes(), []string{"categories", "stack"}) {
t.Fatalf("quota calls = %d, audits = %v, want one charge and one view of the returned fields", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestSearchViewsReportAnExhaustedAllowanceWithoutAWrite(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, false, domain.ScenarioEmployer)
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID)
if err != nil {
return err
}
allowed, err := views.Reserve(ctx, uuid.New())
if err != nil || allowed {
t.Fatalf("Reserve() = %v, %v, want a refusal without an error", allowed, err)
}
return nil
})
if err != nil || len(fixture.contact.audits) != 0 {
t.Fatalf("error = %v, audits = %v, want no record for a refused view", err, fixture.contact.audits)
}
candidate := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate)
err = candidate.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := candidate.service.BeginSearchViews(ctx, unit, candidate.actorID, candidate.organizationID)
return err
})
if !errors.Is(err, ErrForbidden) {
t.Fatalf("BeginSearchViews(candidate) error = %v, want ErrForbidden", err)
}
}