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)
}
}
@@ -47,6 +47,8 @@ func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quot
return repository.decision, repository.err
}
func (repository *quotaTestRepository) LockOrganization(context.Context, uuid.UUID) error { return nil }
func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
repository.cardViewCalls++
repository.cardViewQuota = quota
@@ -67,6 +67,18 @@ func (repository *evidenceTestRepository) ListOrganizationFacts(
return nil, nil
}
func (repository *evidenceTestRepository) ListOrganizationFactsBatch(
context.Context, uuid.UUID, []outbound.EvidenceCandidateCategories,
) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) {
return nil, errors.New("the single organization read must not use the batch read")
}
func (repository *evidenceTestRepository) CountComparableRealCategories(
context.Context, []outbound.CategoryKey,
) (map[outbound.CategoryKey]int64, error) {
return nil, errors.New("the evidence read must not count cohorts")
}
func (repository *evidenceTestRepository) ListPreviewFacts(context.Context, uuid.UUID, []domain.CandidateViewCategory) ([]domain.EvidenceOrganizationFact, error) {
return nil, errors.New("the organization read must not read the preview")
}
@@ -0,0 +1,150 @@
package matching
import (
"slices"
"lincodex/backend/internal/domain"
)
// explanationInput is what the explanation reads: the computed scores of the
// entry and the facts of the card. It builds nothing that the scores did not
// compute, so a change of the requirements moves the numbers and the
// explanation together.
type explanationInput struct {
confirmed bool
declaredGrade *domain.GradeCode
policy domain.MatchingPolicy
scores scores
context PublicContext
// requestedFormats are the work formats that the search asks for; it is
// empty when neither the need nor a filter names any.
requestedFormats []domain.QuestionnaireWorkFormat
// needDomainConfirmed tells why the domain is unknown: the card has no
// domain, and the need may not have confirmed one either.
needDomainConfirmed bool
// percentileReason is the reason that the percentile is null; the zero
// value means the cohort is below the minimum.
percentileReason UnknownReason
}
// explain builds the bounded, templated explanation and the unknown flags.
// An unknown component appears only in the flags and is never shown as a
// verdict about the person, and the absence of FSP data is neither a gap nor
// an unknown here: the competition component is zero by definition.
func explain(input explanationInput) ([]EvidenceItem, []UnknownFlag) {
return evidenceSummary(input), unknownFlags(input)
}
func evidenceSummary(input explanationInput) []EvidenceItem {
items := make([]EvidenceItem, 0, 6)
if input.confirmed {
items = append(items, EvidenceItem{Code: EvidenceConfirmedCategory, State: EvidenceStateSupports})
}
if input.declaredGrade != nil {
items = append(items, EvidenceItem{Code: EvidenceDeclaredGrade, State: EvidenceStateDeclaredOnly})
}
if state, ok := skillGroupState(input, true); ok {
items = append(items, EvidenceItem{Code: EvidenceRequiredSkill, State: state})
}
if state, ok := skillGroupState(input, false); ok {
items = append(items, EvidenceItem{Code: EvidenceDesiredSkill, State: state})
}
if len(input.requestedFormats) > 0 && len(input.context.WorkFormats) > 0 {
state := EvidenceStateGap
for _, format := range input.context.WorkFormats {
if slices.Contains(input.requestedFormats, format) {
state = EvidenceStateSupports
break
}
}
items = append(items, EvidenceItem{Code: EvidenceWorkConditionsMatch, State: state})
}
if compatibility := input.context.SalaryCompatibility; compatibility != nil {
state := EvidenceStateGap
if *compatibility == domain.CandidateViewSalaryCompatible {
state = EvidenceStateSupports
}
items = append(items, EvidenceItem{Code: EvidenceSalaryCompatibility, State: state})
}
return items
}
// skillGroupState summarizes the skills of one weight class from their
// computed contributions. A skill is supported by a measurement that reaches
// the policy threshold, declared when only a stated claim carries it, partial
// when a measurement exists but stays below the threshold, and a gap when
// nothing counts. The group is supported or a gap only when every skill is.
func skillGroupState(input explanationInput, required bool) (EvidenceState, bool) {
threshold := int64(input.policy.NearSkillThreshold) * picoPerBasisPoint
var total, supported, declared, gaps int
for _, skill := range input.scores.skills {
if skill.required != required {
continue
}
total++
switch {
case skill.pico == 0:
gaps++
case skill.measured && skill.pico >= threshold:
supported++
case !skill.measured:
declared++
}
}
switch {
case total == 0:
return "", false
case supported == total:
return EvidenceStateSupports, true
case gaps == total:
return EvidenceStateGap, true
case declared == total:
return EvidenceStateDeclaredOnly, true
default:
return EvidenceStatePartial, true
}
}
// unknownFlags lists, in the order of the contract's component list, every
// value that is neutral or absent. A confirmed entry shows the neutral T and
// the neutral freshness and responsiveness; an unconfirmed entry shows that
// the specialization has no confirmation instead.
func unknownFlags(input explanationInput) []UnknownFlag {
flags := make([]UnknownFlag, 0, 9)
flags = append(flags, UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable})
if input.confirmed {
reason := input.percentileReason
if reason == "" {
reason = ReasonCohortBelow30
}
flags = append(flags, UnknownFlag{Component: UnknownPercentile, Reason: reason})
} else {
flags = append(flags, UnknownFlag{Component: UnknownAssessment, Reason: ReasonNoConfirmationForSpecialization})
}
if input.confirmed {
flags = append(flags,
UnknownFlag{Component: UnknownFreshness, Reason: ReasonNoFreshnessHistory},
UnknownFlag{Component: UnknownResponsiveness, Reason: ReasonNoResponseHistory},
)
}
if input.context.ExperienceBand == nil {
flags = append(flags, UnknownFlag{Component: UnknownExperienceBand, Reason: ReasonNotInPublicCard})
}
if len(input.context.WorkFormats) == 0 {
flags = append(flags, UnknownFlag{Component: UnknownWorkFormats, Reason: ReasonNotInPublicCard})
}
if input.context.SalaryCompatibility == nil {
flags = append(flags, UnknownFlag{Component: UnknownSalaryCompatibility, Reason: ReasonNotInPublicCard})
}
flags = append(flags, domainFlag(input))
return flags
}
// domainFlag says why Dom is the neutral value. The anonymous card never
// carries a domain, so a confirmed need domain cannot be compared with it.
func domainFlag(input explanationInput) UnknownFlag {
if input.needDomainConfirmed {
return UnknownFlag{Component: UnknownDomain, Reason: ReasonNotInPublicCard}
}
return UnknownFlag{Component: UnknownDomain, Reason: ReasonNeedFieldUnconfirmed}
}
@@ -0,0 +1,67 @@
package matching
import (
"slices"
"lincodex/backend/internal/domain"
)
// accepts reports whether one candidate specialization passes every explicit
// filter and the effective specialization. A filter that names a confirmed
// grade or category excludes every unconfirmed specialization, and a
// declaration never satisfies a confirmed filter. An unknown card value never
// satisfies a condition.
func (filters Filters) accepts(entry candidateEntry, specialization *domain.SpecializationCode) bool {
if specialization != nil && entry.specialization != *specialization {
return false
}
return filters.acceptsConfirmation(entry) && filters.acceptsCard(entry)
}
func (filters Filters) acceptsConfirmation(entry candidateEntry) bool {
confirmed := entry.category != nil
if filters.ConfirmedGrade != nil && (!confirmed || entry.category.Grade != *filters.ConfirmedGrade) {
return false
}
if category := filters.ConfirmedCategory; category != nil {
if !confirmed || entry.category.Specialization != category.Specialization || entry.category.Grade != category.Grade {
return false
}
}
if status := filters.ConfirmationStatus; status != nil && (*status == domain.CandidateViewConfirmationConfirmed) != confirmed {
return false
}
return filters.DeclaredGrade == nil || (entry.declaredGrade != nil && *entry.declaredGrade == *filters.DeclaredGrade)
}
func (filters Filters) acceptsCard(entry candidateEntry) bool {
for _, tag := range filters.Stack {
if !slices.Contains(entry.card.Skills, tag) {
return false
}
}
return filters.Conditions.accepts(entry.card)
}
func (conditions *Conditions) accepts(card domain.AnonymousCandidateViewDTO) bool {
if conditions == nil {
return true
}
if len(conditions.WorkFormats) > 0 {
offered := false
for _, format := range card.WorkFormats {
if slices.Contains(conditions.WorkFormats, format) {
offered = true
break
}
}
if !offered {
return false
}
}
if conditions.SalaryCompatibility != nil &&
(card.SalaryCompatibility == nil || *card.SalaryCompatibility != *conditions.SalaryCompatibility) {
return false
}
return true
}
@@ -0,0 +1,119 @@
package matching
import (
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func gradePointer(grade domain.GradeCode) *domain.GradeCode { return &grade }
func TestEntriesOfKeepsEverySpecializationSeparate(t *testing.T) {
middle, junior := domain.GradeMiddle, domain.GradeJunior
card := domain.AnonymousCandidateViewDTO{
Pseudonym: "handle",
Categories: []domain.CandidateViewCategory{
{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard},
},
SelfAssessment: []domain.CandidateViewSelfAssessment{
{Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed, DeclaredGrade: &junior},
{Specialization: domain.SpecializationNetworkEngineer, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed, DeclaredGrade: &middle},
// Confirmed in the self-assessment but not shown as a category:
// the card does not publish that confirmation, so no entry claims it.
{Specialization: domain.SpecializationQA, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed},
},
}
entries := entriesOf(domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: card})
got := make([]string, 0, len(entries))
for _, entry := range entries {
state := "unconfirmed"
if entry.category != nil {
state = "confirmed"
}
got = append(got, string(entry.specialization)+":"+state)
}
if want := []string{"backend:confirmed", "network_engineer:unconfirmed"}; !slices.Equal(got, want) {
t.Fatalf("entries = %v, want %v", got, want)
}
if entries[0].declaredGrade == nil || *entries[0].declaredGrade != domain.GradeJunior ||
entries[1].declaredGrade == nil || *entries[1].declaredGrade != domain.GradeMiddle {
t.Fatalf("declared grades = %v and %v, want each specialization's own", entries[0].declaredGrade, entries[1].declaredGrade)
}
}
func TestFiltersKeepTheConfirmedAndDeclaredClaimsApart(t *testing.T) {
remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}
compatible := domain.CandidateViewSalaryCompatible
confirmed := candidateEntry{
specialization: domain.SpecializationBackend,
category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle},
declaredGrade: gradePointer(domain.GradeJunior),
card: domain.AnonymousCandidateViewDTO{Skills: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}, WorkFormats: remote, SalaryCompatibility: &compatible},
}
unconfirmed := candidateEntry{
specialization: domain.SpecializationBackend, declaredGrade: gradePointer(domain.GradeMiddle),
card: domain.AnonymousCandidateViewDTO{WorkFormats: remote},
}
backend := domain.SpecializationBackend
frontend := domain.SpecializationFrontend
status := func(value domain.CandidateViewConfirmationStatus) *domain.CandidateViewConfirmationStatus {
return &value
}
tests := []struct {
name string
filters Filters
specialization *domain.SpecializationCode
wantConfirmed, wantUnconf bool
}{
{name: "no filter", filters: Filters{}, wantConfirmed: true, wantUnconf: true},
{name: "specialization", filters: Filters{}, specialization: &backend, wantConfirmed: true, wantUnconf: true},
{name: "another specialization", filters: Filters{}, specialization: &frontend},
{name: "confirmed grade excludes the unconfirmed", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeMiddle)}, wantConfirmed: true},
{name: "a declared grade never satisfies a confirmed grade", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeJunior)}},
{
name: "confirmed category",
filters: Filters{ConfirmedCategory: &GradeFilter{Specialization: backend, Grade: domain.GradeMiddle}},
wantConfirmed: true,
},
{name: "confirmation status confirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationConfirmed)}, wantConfirmed: true},
{name: "confirmation status unconfirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationUnconfirmed)}, wantUnconf: true},
{name: "declared grade", filters: Filters{DeclaredGrade: gradePointer(domain.GradeMiddle)}, wantUnconf: true},
{
name: "every stack tag is required",
filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}},
wantConfirmed: true,
},
{name: "a stack tag the card lacks", filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillDocker}}},
{name: "work format", filters: Filters{Conditions: &Conditions{WorkFormats: remote}}, wantConfirmed: true, wantUnconf: true},
{
name: "an unknown salary compatibility never satisfies the condition",
filters: Filters{Conditions: &Conditions{SalaryCompatibility: &compatible}}, wantConfirmed: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := test.filters.accepts(confirmed, test.specialization); got != test.wantConfirmed {
t.Errorf("accepts(confirmed) = %v, want %v", got, test.wantConfirmed)
}
if got := test.filters.accepts(unconfirmed, test.specialization); got != test.wantUnconf {
t.Errorf("accepts(unconfirmed) = %v, want %v", got, test.wantUnconf)
}
})
}
}
func TestEffectiveSpecializationNeverMergesTwoDifferentOnes(t *testing.T) {
backend, frontend := domain.SpecializationBackend, domain.SpecializationFrontend
if got, ok := effectiveSpecialization(&backend, &frontend); ok || got != nil {
t.Fatalf("effectiveSpecialization(backend, frontend) = %v, %v, want an empty search", got, ok)
}
if got, ok := effectiveSpecialization(nil, &frontend); !ok || got == nil || *got != frontend {
t.Fatalf("effectiveSpecialization(nil, frontend) = %v, %v, want the need specialization", got, ok)
}
if got, ok := effectiveSpecialization(nil, nil); !ok || got != nil {
t.Fatalf("effectiveSpecialization(nil, nil) = %v, %v, want no restriction", got, ok)
}
}
@@ -0,0 +1,126 @@
package matching
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// cohortEvidence answers the cohort count and no fact.
type cohortEvidence struct {
outbound.EvidenceRepository
counts map[outbound.CategoryKey]int64
asked [][]outbound.CategoryKey
}
func (evidence *cohortEvidence) CountComparableRealCategories(
_ context.Context, categories []outbound.CategoryKey,
) (map[outbound.CategoryKey]int64, error) {
evidence.asked = append(evidence.asked, categories)
return evidence.counts, nil
}
type cohortUnit struct {
outbound.UnitOfWork
evidence *cohortEvidence
}
func (unit cohortUnit) Evidence() outbound.EvidenceRepository { return unit.evidence }
func confirmedCard(specialization domain.SpecializationCode, grade domain.GradeCode) domain.VisibleCandidateCard {
return domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: domain.AnonymousCandidateViewDTO{
Pseudonym: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
Categories: []domain.CandidateViewCategory{{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard}},
}}
}
func TestRankKeepsTheNeutralTWhenTheRealCohortReachesTheMinimum(t *testing.T) {
policy := domain.DemoMatchingPolicy()
backendIntern := outbound.CategoryKey{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}
frontendJunior := outbound.CategoryKey{Specialization: domain.SpecializationFrontend, Grade: domain.GradeJunior}
evidence := &cohortEvidence{counts: map[outbound.CategoryKey]int64{
backendIntern: int64(policy.PercentileMinCohort),
frontendJunior: int64(policy.PercentileMinCohort) - 1,
}}
var logs bytes.Buffer
service := &Service{logger: slog.New(slog.NewTextHandler(&logs, nil))}
cards := []domain.VisibleCandidateCard{
confirmedCard(domain.SpecializationBackend, domain.GradeIntern),
confirmedCard(domain.SpecializationBackend, domain.GradeIntern),
confirmedCard(domain.SpecializationFrontend, domain.GradeJunior),
}
ranked, err := service.rank(context.Background(), cohortUnit{evidence: evidence}, Request{}, searchBasis{}, policy, cards)
if err != nil {
t.Fatalf("rank() error = %v, want a result whatever the real cohort size", err)
}
if len(ranked.main) != 3 {
t.Fatalf("main = %d entries, want 3", len(ranked.main))
}
// Only the categories of the accepted entries are counted, each once.
if len(evidence.asked) != 1 || len(evidence.asked[0]) != 2 {
t.Fatalf("cohort questions = %v, want one question for the two categories of the entries", evidence.asked)
}
reasons := map[domain.SpecializationCode]UnknownReason{}
for _, item := range ranked.main {
for _, flag := range item.entry.UnknownFlags {
if flag.Component == UnknownPercentile {
reasons[item.entry.Specialization] = flag.Reason
}
}
if item.entry.Components.Percentile != nil || microToFloat(item.rank) != item.entry.Components.RankScore {
t.Fatalf("entry %+v has a percentile or a rank that is not the neutral-T rank", item.entry.Components)
}
// T is the neutral 0.5 in every case: Cov, Dom, Sem 0.5 give S = 0.45125.
if item.entry.Components.RankScore != 0.45125 {
t.Fatalf("rank score = %v, want 0.45125 with the neutral T", item.entry.Components.RankScore)
}
}
if reasons[domain.SpecializationBackend] != ReasonPercentileNotComputed || reasons[domain.SpecializationFrontend] != ReasonCohortBelow30 {
t.Fatalf("percentile reasons = %v, want not computed at the minimum and below 30 under it", reasons)
}
if strings.Count(logs.String(), "reached the percentile minimum") != 1 || !strings.Contains(logs.String(), "specialization=backend") {
t.Fatalf("log = %q, want one warning for the one category that reached the minimum", logs.String())
}
}
// repeatingTransactor fails with a visibility change a number of times and then
// succeeds without running the work.
type repeatingTransactor struct {
failures int
calls int
}
func (transactor *repeatingTransactor) WithinTransaction(context.Context, func(context.Context, outbound.UnitOfWork) error) error {
transactor.calls++
if transactor.calls <= transactor.failures {
return fmt.Errorf("lock the cohort: %w", outbound.ErrConcurrentVisibilityChange)
}
return nil
}
func TestSearchRepeatsAfterAConcurrentVisibilityChangeAFewTimes(t *testing.T) {
request := Request{ActorID: uuid.New(), OrganizationID: uuid.New()}
for _, test := range []struct {
failures, calls int
wantErr bool
}{{0, 1, false}, {2, 3, false}, {3, 3, true}} {
transactor := &repeatingTransactor{failures: test.failures}
service := &Service{transactor: transactor}
_, err := service.Search(context.Background(), request)
if transactor.calls != test.calls || (err != nil) != test.wantErr ||
(err != nil && !errors.Is(err, outbound.ErrConcurrentVisibilityChange)) {
t.Errorf("%d failures: %d attempts, error %v; want %d attempts, error %v", test.failures, transactor.calls, err, test.calls, test.wantErr)
}
}
}
@@ -0,0 +1,129 @@
package matching
import (
"context"
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// viewsFake charges a fixed number of distinct candidates and records what it
// is asked to write.
type viewsFake struct {
allowance int
reserved map[uuid.UUID]bool
attempts []uuid.UUID
recorded map[uuid.UUID][]domain.CardField
order []uuid.UUID
}
func newViewsFake(allowance int) *viewsFake {
return &viewsFake{allowance: allowance, reserved: map[uuid.UUID]bool{}, recorded: map[uuid.UUID][]domain.CardField{}}
}
func (views *viewsFake) Reserve(_ context.Context, candidateID uuid.UUID) (bool, error) {
views.attempts = append(views.attempts, candidateID)
if views.reserved[candidateID] {
return true, nil
}
if len(views.reserved) >= views.allowance {
return false, nil
}
views.reserved[candidateID] = true
return true, nil
}
func (views *viewsFake) Record(_ context.Context, candidateID uuid.UUID, fields []domain.CardField) error {
views.recorded[candidateID] = fields
views.order = append(views.order, candidateID)
return nil
}
func revealService(views *viewsFake) *Service {
return &Service{views: func(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID) (ViewSession, error) {
return views, nil
}}
}
func confirmedItem(id uuid.UUID) rankedEntry {
band := domain.CandidateExperienceBandOneToThree
return rankedEntry{candidate: id, entry: Entry{
Specialization: domain.SpecializationBackend,
Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior},
PublicContext: PublicContext{ExperienceBand: &band, Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo}},
}}
}
func declaredItem(id uuid.UUID, specialization domain.SpecializationCode) rankedEntry {
return rankedEntry{candidate: id, entry: Entry{Specialization: specialization}}
}
func TestRevealCutsEachGroupAndRecordsTheFieldsReturned(t *testing.T) {
first, second := uuid.New(), uuid.New()
policy := domain.DemoMatchingPolicy()
policy.MaxResultsPerGroup = 2
views := newViewsFake(10)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, policy, groups{
main: []rankedEntry{confirmedItem(first), confirmedItem(second), confirmedItem(uuid.New())},
unconfirmed: []rankedEntry{declaredItem(first, domain.SpecializationNetworkEngineer)},
})
if err != nil {
t.Fatalf("reveal() error = %v", err)
}
if len(result.Main) != 2 || len(result.Unconfirmed) != 1 || !result.Truncated {
t.Fatalf("result = %d main, %d unconfirmed, truncated %v, want the group cut at 2 and flagged", len(result.Main), len(result.Unconfirmed), result.Truncated)
}
// The first candidate appears twice and is charged once; the dropped third
// entry is never charged.
if len(views.reserved) != 2 || !views.reserved[first] || !views.reserved[second] {
t.Fatalf("reserved = %v, want the two returned candidates", views.reserved)
}
// The fields are those that the returned entries show: the category, the
// stack, and the experience of the Backend entry plus the self-assessment of
// the Networks entry.
want := []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, domain.CardFieldSelfAssessment}
if !slices.Equal(views.recorded[first], want) {
t.Fatalf("recorded fields of the first candidate = %v, want %v", views.recorded[first], want)
}
if got := views.recorded[second]; !slices.Equal(got, want[:3]) {
t.Fatalf("recorded fields of the second candidate = %v, want %v", got, want[:3])
}
}
func TestRevealReturnsThePrefixThatIsPaidForWhenTheAllowanceEnds(t *testing.T) {
ids := []uuid.UUID{uuid.New(), uuid.New(), uuid.New(), uuid.New()}
views := newViewsFake(2)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
main: []rankedEntry{confirmedItem(ids[0])},
near: []rankedEntry{confirmedItem(ids[1]), confirmedItem(ids[2])},
unconfirmed: []rankedEntry{declaredItem(ids[0], domain.SpecializationNetworkEngineer), declaredItem(ids[3], domain.SpecializationQA)},
})
if err != nil {
t.Fatalf("reveal() error = %v", err)
}
if len(result.Main) != 1 || len(result.Near) != 1 || len(result.Unconfirmed) != 0 || !result.Truncated {
t.Fatalf("result = %d/%d/%d truncated %v, want the entries before the refusal and nothing after it",
len(result.Main), len(result.Near), len(result.Unconfirmed), result.Truncated)
}
if len(views.reserved) != 2 || len(views.recorded) != 2 || views.reserved[ids[2]] || views.reserved[ids[3]] {
t.Fatalf("reserved %v, recorded %v, want only the two paid candidates", views.reserved, views.recorded)
}
}
func TestRevealDoesNotFlagACompleteResult(t *testing.T) {
views := newViewsFake(5)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
main: []rankedEntry{confirmedItem(uuid.New())},
})
if err != nil || result.Truncated || len(result.Main) != 1 {
t.Fatalf("reveal() = %+v, %v, want one entry that is not truncated", result, err)
}
empty, err := revealService(newViewsFake(0)).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{})
if err != nil || empty.Truncated || len(empty.Main)+len(empty.Near)+len(empty.Unconfirmed) != 0 {
t.Fatalf("an empty search = %+v, %v, want an empty result that is not truncated", empty, err)
}
}
+171
View File
@@ -0,0 +1,171 @@
package matching
import (
"lincodex/backend/internal/domain"
)
// Scores are computed in integers so that the same data and policy always give
// the same order on every platform. A policy share is BasisPoints (1e-4); a
// component is stored in micro units (1e-6), the precision at which results
// are rounded and compared; a skill contribution keeps the exact product of
// three shares in pico units (1e-12).
const (
microPerUnit int64 = 1_000_000
bpPerUnit int64 = 10_000
picoPerBasisPoint int64 = 100_000_000
microPerBasisPoint int64 = 100
)
// requestedSkill is one skill that a need or a stack filter asks for. A skill
// without a taxonomy code cannot match any evidence: the platform has no
// reviewed mapping for it, so it stays a gap and never an invented match.
type requestedSkill struct {
code string
required bool
}
// evidenceSource is one permitted piece of evidence of a candidate: either a
// stated stack tag of the card (trust 0, a claim) or the one assessment fact
// that supports the confirmed category.
type evidenceSource struct {
code string
trust domain.EvidenceTrust
attribution domain.EvidenceAttribution
measured bool
}
// skillOutcome is the contribution of one requested skill and what it rests
// on. The explanation reads these exact values.
type skillOutcome struct {
required bool
pico int64
// measured is true when the best evidence is a measurement and false when
// it is a stated claim or when there is none.
measured bool
}
// scores are the computed components of one entry, in micro units.
type scores struct {
skills []skillOutcome
coverage int64
domain int64
semantics int64
fit int64
t int64
competition int64
strength int64
freshness int64
responsive int64
rank int64
}
// scoreInput is everything a score depends on.
type scoreInput struct {
// confirmed selects the confirmed-profile model. An unconfirmed profile
// gets only coverage and fit: it has no theta, T, P, or rank score, so
// those values are never computed for it.
confirmed bool
policy domain.MatchingPolicy
skills []requestedSkill
evidence []evidenceSource
}
// computeScores applies the FR09 model. Unknown components are neutral: Dom,
// Sem, Fr, and Rsp use the neutral value, T is neutral because there is no
// comparable real cohort, and V is zero because no competition evidence
// exists, which is not a penalty.
func computeScores(input scoreInput) scores {
policy := input.policy
neutral := int64(policy.NeutralUnknown) * microPerBasisPoint
result := scores{
domain: neutral, semantics: neutral, t: neutral, freshness: neutral, responsive: neutral,
}
result.skills = make([]skillOutcome, 0, len(input.skills))
var weighted, weights int64
for _, skill := range input.skills {
pico, measured := skillContribution(policy, skill, input.evidence)
weight := int64(policy.DesiredSkillWeight)
if skill.required {
weight = int64(policy.RequiredSkillWeight)
}
weighted += weight * pico
weights += weight
result.skills = append(result.skills, skillOutcome{required: skill.required, pico: pico, measured: measured})
}
// An empty request has nothing to cover; it uses the neutral value instead
// of dividing by zero.
result.coverage = neutral
if weights > 0 {
result.coverage = roundedQuotient(weighted, weights*microPerUnit)
}
result.fit = roundedQuotient(
int64(policy.FitCoverageWeight)*result.coverage+
int64(policy.FitDomainWeight)*result.domain+
int64(policy.FitSemanticsWeight)*result.semantics,
bpPerUnit)
if !input.confirmed {
result.t, result.freshness, result.responsive = 0, 0, 0
return result
}
// P = T + boost * (1 - T) * V, with V = 0 without competition evidence.
result.strength = result.t + roundedQuotient(
int64(policy.CompetitionBoost)*(microPerUnit-result.t)*result.competition, bpPerUnit*microPerUnit)
rank := roundedQuotient(
int64(policy.RankFitWeight)*result.fit+int64(policy.RankStrengthWeight)*result.strength, bpPerUnit)
rank = multiplyMicro(rank, blendedMultiplier(policy.FreshnessFloor, result.freshness))
result.rank = multiplyMicro(rank, blendedMultiplier(policy.ResponsivenessFloor, result.responsive))
return result
}
// skillContribution is the best product of the trust, attribution, and
// relation coefficients over the evidence, not their sum, so a repeated tag or
// a second piece of the same kind never raises the contribution. A tie goes to
// the measurement, so the explanation names the stronger basis.
func skillContribution(policy domain.MatchingPolicy, skill requestedSkill, evidence []evidenceSource) (int64, bool) {
if skill.code == "" {
return 0, false
}
var best int64
var measured bool
for _, source := range evidence {
trust, trustOK := policy.TrustCoefficient(source.trust)
attribution, attributionOK := policy.AttributionCoefficient(source.attribution)
if !trustOK || !attributionOK {
continue
}
relation := policy.RelationCoefficient(policy.RelateSkill(skill.code, source.code))
value := int64(trust) * int64(attribution) * int64(relation)
if value > best || (value == best && value > 0 && source.measured && !measured) {
best, measured = value, source.measured
}
}
return best, measured
}
// belongsToNearGroup reports whether a requested required skill earns less
// than the policy threshold, which moves a confirmed profile to "near".
func (result scores) belongsToNearGroup(policy domain.MatchingPolicy) bool {
threshold := int64(policy.NearSkillThreshold) * picoPerBasisPoint
for _, skill := range result.skills {
if skill.required && skill.pico < threshold {
return true
}
}
return false
}
// blendedMultiplier is floor + (1 - floor) * x, in micro units.
func blendedMultiplier(floor domain.BasisPoints, x int64) int64 {
return int64(floor)*microPerBasisPoint + roundedQuotient((bpPerUnit-int64(floor))*x, bpPerUnit)
}
func multiplyMicro(left, right int64) int64 {
return roundedQuotient(left*right, microPerUnit)
}
// roundedQuotient divides non-negative integers and rounds half up.
func roundedQuotient(numerator, denominator int64) int64 {
return (numerator + denominator/2) / denominator
}
func microToFloat(value int64) float64 { return float64(value) / float64(microPerUnit) }
@@ -0,0 +1,283 @@
package matching
import (
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
onlineBackendFact = evidenceSource{code: "backend", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true}
statedGo = evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
statedKafka = evidenceSource{code: "kafka", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
)
func required(code string) requestedSkill { return requestedSkill{code: code, required: true} }
func desired(code string) requestedSkill { return requestedSkill{code: code} }
func TestComputeScoresFollowsTheFR09Formulas(t *testing.T) {
policy := domain.DemoMatchingPolicy()
tests := []struct {
name string
confirmed bool
skills []requestedSkill
evidence []evidenceSource
coverage int64
fit int64
rank int64
near bool
}{
{
// 0.6 online trust * 1.0 personal * 0.4 broader relation = 0.24:
// Cov 0.24, Fit 0.75*0.24+0.15*0.5+0.10*0.5 = 0.305, P = T = 0.5,
// S = (0.5*0.305+0.5*0.5) * 0.95 * 0.95 = 0.363256.
name: "a broad measurement under a requested technology is below the near threshold", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{onlineBackendFact},
coverage: 240000, fit: 305000, rank: 363256, near: true,
},
{
// A stated tag is a claim with trust 0.25.
name: "a stated tag reaches the threshold exactly", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo},
coverage: 250000, fit: 312500, rank: 366641, near: false,
},
{
name: "the best evidence counts once, not the sum of duplicates", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo, statedGo, onlineBackendFact, onlineBackendFact},
coverage: 250000, fit: 312500, rank: 366641, near: false,
},
{
name: "weights are 2 for required and 1 for desired", confirmed: true,
skills: []requestedSkill{required("go"), desired("kafka")},
evidence: []evidenceSource{onlineBackendFact, statedKafka},
coverage: 243333, fit: 307500, rank: 364385, near: true,
},
{
name: "an empty request is neutral and never divides by zero", confirmed: true,
skills: nil, evidence: []evidenceSource{onlineBackendFact},
coverage: 500000, fit: 500000, rank: 451250, near: false,
},
{
// Cov 0: Fit 0.125, S = (0.5*0.125+0.25) * 0.9025 = 0.282031.
name: "a skill without a taxonomy mapping is a gap", confirmed: true,
skills: []requestedSkill{required("")}, evidence: []evidenceSource{onlineBackendFact, statedGo},
coverage: 0, fit: 125000, rank: 282031, near: true,
},
{
name: "an unconfirmed profile has fit and coverage only", confirmed: false,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo},
coverage: 250000, fit: 312500, rank: 0, near: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := computeScores(scoreInput{confirmed: test.confirmed, policy: policy, skills: test.skills, evidence: test.evidence})
if got.coverage != test.coverage || got.fit != test.fit {
t.Fatalf("coverage/fit = %d/%d, want %d/%d", got.coverage, got.fit, test.coverage, test.fit)
}
if test.confirmed && got.rank != test.rank {
t.Fatalf("rank = %d, want %d", got.rank, test.rank)
}
if got.belongsToNearGroup(policy) != test.near {
t.Fatalf("near = %v, want %v", got.belongsToNearGroup(policy), test.near)
}
})
}
}
func TestComputeScoresNeverGivesAnUnconfirmedProfileStrength(t *testing.T) {
got := computeScores(scoreInput{
confirmed: false, policy: domain.DemoMatchingPolicy(), skills: []requestedSkill{required("go")},
evidence: []evidenceSource{statedGo},
})
if got.t != 0 || got.strength != 0 || got.rank != 0 || got.freshness != 0 || got.responsive != 0 {
t.Fatalf("unconfirmed scores = %+v, want no T, P, S, or rank multipliers", got)
}
}
func TestComputeScoresIsRepeatable(t *testing.T) {
input := scoreInput{
confirmed: true, policy: domain.DemoMatchingPolicy(),
skills: []requestedSkill{required("go"), required("postgresql"), desired("kafka"), desired("docker")},
evidence: []evidenceSource{onlineBackendFact, statedGo, statedKafka},
}
first := computeScores(input)
for range 20 {
if again := computeScores(input); !slices.Equal(again.skills, first.skills) || again.rank != first.rank || again.fit != first.fit {
t.Fatalf("computeScores() changed between runs: %+v then %+v", first, again)
}
}
}
func TestSkillContributionPrefersAMeasurementOnATie(t *testing.T) {
policy := domain.DemoMatchingPolicy()
policy.TrustStated = policy.TrustOnline
measured := evidenceSource{code: "go", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true}
stated := evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
for _, evidence := range [][]evidenceSource{{stated, measured}, {measured, stated}} {
if _, isMeasured := skillContribution(policy, required("go"), evidence); !isMeasured {
t.Fatalf("skillContribution(%v) reported a claim although an equal measurement exists", evidence)
}
}
}
func TestRequestedSkillsCountEachCodeOnce(t *testing.T) {
goCode, kafkaCode := "go", "kafka"
confirmedSkill := func(name string, code *string) domain.NeedSkill {
return domain.NeedSkill{Name: name, TaxonomyCode: code, Status: domain.NeedItemConfirmed}
}
skills := requestedSkills(
[]domain.NeedSkill{
confirmedSkill("Go", &goCode), confirmedSkill("Golang", &goCode), confirmedSkill("Temporal", nil), confirmedSkill(" temporal ", nil),
{Name: "Rust", Status: domain.NeedItemExtracted},
},
[]domain.NeedSkill{confirmedSkill("Kafka", &kafkaCode), confirmedSkill("Go again", &goCode)},
[]domain.CandidateViewSkillCode{domain.CandidateViewSkillKafka, domain.CandidateViewSkillDocker},
)
want := []requestedSkill{
{code: "go", required: true}, {required: true}, {code: "kafka", required: true}, {code: "docker", required: true},
}
if !slices.Equal(skills, want) {
t.Fatalf("requestedSkills() = %+v, want %+v", skills, want)
}
}
func TestExplanationReadsTheComputedContributions(t *testing.T) {
policy := domain.DemoMatchingPolicy()
explainWith := func(confirmed bool, skills []requestedSkill, evidence []evidenceSource, context PublicContext, formats []domain.QuestionnaireWorkFormat) []EvidenceItem {
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: skills, evidence: evidence})
items, _ := explain(explanationInput{confirmed: confirmed, policy: policy, scores: computed, context: context, requestedFormats: formats})
return items
}
remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}
office := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatOffice}
tests := []struct {
name string
got []EvidenceItem
want []EvidenceItem
}{
{
name: "all required skills carried by measurements",
got: explainWith(true, []requestedSkill{required("backend")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStateSupports}},
},
{
name: "a measurement below the threshold is partial",
got: explainWith(true, []requestedSkill{required("go")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStatePartial}},
},
{
name: "only stated tags are declared",
got: explainWith(false, []requestedSkill{required("go")}, []evidenceSource{statedGo}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateDeclaredOnly}},
},
{
name: "nothing carries the skills",
got: explainWith(false, []requestedSkill{required("go"), desired("kafka")}, nil, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateGap}, {EvidenceDesiredSkill, EvidenceStateGap}},
},
{
name: "a mix of covered and missing skills is partial",
got: explainWith(false, []requestedSkill{required("go"), required("kafka")}, []evidenceSource{statedGo}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStatePartial}},
},
{
name: "work formats are compared with the request",
got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, office),
want: []EvidenceItem{{EvidenceWorkConditionsMatch, EvidenceStateGap}},
},
{
name: "no request for skills or formats gives no item",
got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, nil),
want: []EvidenceItem{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if len(test.got) == 0 && len(test.want) == 0 {
return
}
if !slices.Equal(test.got, test.want) {
t.Fatalf("evidence summary = %+v, want %+v", test.got, test.want)
}
})
}
}
func TestUnknownFlagsNameNeutralValuesAndNeverFSP(t *testing.T) {
policy := domain.DemoMatchingPolicy()
computed := computeScores(scoreInput{confirmed: true, policy: policy})
_, confirmedFlags := explain(explanationInput{confirmed: true, policy: policy, scores: computed})
wantConfirmed := []UnknownFlag{
{UnknownSemantics, ReasonMLUnavailable}, {UnknownPercentile, ReasonCohortBelow30},
{UnknownFreshness, ReasonNoFreshnessHistory}, {UnknownResponsiveness, ReasonNoResponseHistory},
{UnknownExperienceBand, ReasonNotInPublicCard}, {UnknownWorkFormats, ReasonNotInPublicCard},
{UnknownSalaryCompatibility, ReasonNotInPublicCard}, {UnknownDomain, ReasonNeedFieldUnconfirmed},
}
if !slices.Equal(confirmedFlags, wantConfirmed) {
t.Fatalf("confirmed unknown flags = %+v, want %+v", confirmedFlags, wantConfirmed)
}
band := domain.CandidateExperienceBandOneToThree
compatible := domain.CandidateViewSalaryCompatible
_, unconfirmedFlags := explain(explanationInput{
policy: policy, needDomainConfirmed: true,
context: PublicContext{ExperienceBand: &band, SalaryCompatibility: &compatible, WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}},
})
wantUnconfirmed := []UnknownFlag{
{UnknownSemantics, ReasonMLUnavailable}, {UnknownAssessment, ReasonNoConfirmationForSpecialization},
{UnknownDomain, ReasonNotInPublicCard},
}
if !slices.Equal(unconfirmedFlags, wantUnconfirmed) {
t.Fatalf("unconfirmed unknown flags = %+v, want %+v", unconfirmedFlags, wantUnconfirmed)
}
}
func TestOrderingIsStableAndSeparateForEachGroup(t *testing.T) {
lowID := uuid.MustParse("00000000-0000-0000-0000-000000000001")
highID := uuid.MustParse("00000000-0000-0000-0000-000000000002")
entry := func(id uuid.UUID, specialization domain.SpecializationCode, fit, coverage, rank int64) rankedEntry {
return rankedEntry{
entry: Entry{Specialization: specialization},
candidate: id, fit: fit, coverage: coverage, rank: rank,
}
}
ids := func(items []rankedEntry) []uuid.UUID {
result := make([]uuid.UUID, len(items))
for index, item := range items {
result[index] = item.candidate
}
return result
}
t.Run("equal rank is resolved by coverage and then by the internal identifier", func(t *testing.T) {
items := []rankedEntry{
entry(highID, "backend", 0, 400000, 500000),
entry(lowID, "backend", 0, 400000, 500000),
entry(highID, "devops_sre", 0, 450000, 500000),
}
slices.SortStableFunc(items, compareByRank)
if got := ids(items); !slices.Equal(got, []uuid.UUID{highID, lowID, highID}) || items[0].entry.Specialization != "devops_sre" {
t.Fatalf("order = %v, want higher coverage first, then ascending identifiers", got)
}
})
t.Run("the unconfirmed group uses fit, then coverage, then the identifier", func(t *testing.T) {
items := []rankedEntry{
entry(highID, "qa", 300000, 100000, 999999),
entry(lowID, "qa", 300000, 100000, 1),
entry(highID, "frontend", 400000, 0, 0),
}
slices.SortStableFunc(items, compareByFit)
if items[0].entry.Specialization != "frontend" || items[1].candidate != lowID || items[2].candidate != highID {
t.Fatalf("order = %+v, want fit first and the rank score ignored", items)
}
})
t.Run("two entries of one candidate keep a stable order", func(t *testing.T) {
items := []rankedEntry{entry(lowID, "qa", 0, 0, 0), entry(lowID, "backend", 0, 0, 0)}
slices.SortStableFunc(items, compareByRank)
if items[0].entry.Specialization != "backend" {
t.Fatalf("order = %+v, want the specialization to separate equal entries", items)
}
})
}
+697
View File
@@ -0,0 +1,697 @@
// Package matching ranks the organization-visible candidate bank
// deterministically. It filters by the current visibility rules first, scores
// each candidate specialization with the versioned matching policy, and builds
// the explanation from the same computed components. It reads no contact, no
// raw assessment data, and no hidden minimum, and it consumes no ML result.
package matching
import (
"cmp"
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// VisibleCards returns the current organization-visible cards inside the
// caller's transaction. candidateview.Service.ListVisibleCards provides it;
// bootstrap passes it in so this package depends on no other usecase.
type VisibleCards func(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
) ([]domain.VisibleCandidateCard, error)
// ViewSession charges and records the candidates that one search reveals,
// inside the caller's transaction.
type ViewSession interface {
// Reserve counts the candidate as a distinct card view of the organization.
// A candidate already viewed inside the window is allowed without another
// charge. It reports false and writes nothing once the allowance is used up.
Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error)
// Record appends the access history entry for the fields that were returned.
Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error
}
// BeginViews opens a ViewSession for an authorized actor and organization.
// candidateview.Service.BeginSearchViews provides it through bootstrap.
type BeginViews func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (ViewSession, error)
// Dependencies configure the search service.
type Dependencies struct {
Transactor outbound.Transactor
Cards VisibleCards
Views BeginViews
Clock func() time.Time
// Logger receives the warnings of a search. A nil logger discards them.
Logger *slog.Logger
}
// Service searches and ranks the visible bank.
type Service struct {
transactor outbound.Transactor
cards VisibleCards
views BeginViews
clock func() time.Time
logger *slog.Logger
}
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Cards == nil || deps.Views == nil || deps.Clock == nil {
return nil, fmt.Errorf("matching.NewService - dependencies are missing: %w", ErrServiceMissing)
}
logger := deps.Logger
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return &Service{transactor: deps.Transactor, cards: deps.Cards, views: deps.Views, clock: deps.Clock, logger: logger}, nil
}
// Search returns the groups for one request. Everything runs in one
// transaction: the owner role, the membership, and the candidate visibility are
// checked and locked before any card is read, the need snapshot and the policy
// are read from storage, and the permitted evidence is read through the
// organization-safe projection queries, so no later read can widen what the
// first one allowed.
//
// A search reveals card content, so it is charged like card reads. The whole
// visible bank is ranked, but each group is cut to the policy's
// MaxResultsPerGroup, and no total is returned. Walking the output in the
// order main, near, unconfirmed, each newly revealed candidate is reserved as a
// distinct card view of the organization (a candidate already viewed inside the
// window costs nothing again) and recorded in the candidate's access history
// with the fields actually returned, in the same transaction. When the
// allowance runs out the entries already paid for are returned with Truncated
// set, and nothing is written for the rest.
func (service *Service) Search(ctx context.Context, request Request) (Result, error) {
const location = "matching.Service.Search"
if request.ActorID == uuid.Nil || request.OrganizationID == uuid.Nil {
return Result{}, ErrForbidden
}
var result Result
var err error
// The visible cohort can change while it is locked. The whole search is
// then repeated, a bounded number of times, and the writes of a failed
// attempt roll back with it.
for range maxSearchAttempts {
result, err = service.searchOnce(ctx, request)
if !errors.Is(err, outbound.ErrConcurrentVisibilityChange) {
break
}
}
if err != nil {
return Result{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// maxSearchAttempts bounds the repeats after a concurrent visibility change.
const maxSearchAttempts = 3
func (service *Service) searchOnce(ctx context.Context, request Request) (Result, error) {
const location = "matching.Service.searchOnce"
var result Result
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
// The MVP milestone allows only the active owner; a membership alone
// grants nothing here. The HTTP boundary checks the same rule, and the
// repeat keeps the usecase closed when it is called another way. The
// role is settled before the cohort is read and locked.
// The reservations below take the exclusive organization lock. Taking it
// first, before the share lock of the membership check, keeps two
// searches of one organization from deadlocking on the upgrade, and it
// serializes their charges.
if err := unit.CompanyQuotas().LockOrganization(ctx, request.OrganizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return outbound.ErrOrganizationNotFound
}
return fmt.Errorf("%s - lock organization: %w", location, err)
}
membership, err := unit.Organizations().LockActiveMembership(ctx, request.OrganizationID, request.ActorID)
if err != nil {
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner {
return ErrForbidden
}
cards, err := service.cards(ctx, unit, request.ActorID, request.OrganizationID)
if err != nil {
return err
}
policy, err := service.matchingPolicy(ctx, unit)
if err != nil {
return err
}
basis, err := loadBasis(ctx, unit, request)
if err != nil {
return err
}
ranked, err := service.rank(ctx, unit, request, basis, policy, cards)
if err != nil {
return err
}
result, err = service.reveal(ctx, unit, request, policy, ranked)
return err
})
if err != nil {
return Result{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func (service *Service) matchingPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.MatchingPolicy, error) {
const location = "matching.Service.matchingPolicy"
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, service.clock().UTC())
if err != nil {
return domain.MatchingPolicy{}, fmt.Errorf("%s - read effective product policy: %w", location, err)
}
policy := version.Policy().Matching
if policy == nil {
return domain.MatchingPolicy{}, fmt.Errorf("%s - the effective product policy has no matching section, publish it with the policy-publish command: %w", location, ErrPolicyUnavailable)
}
return *policy, nil
}
// searchBasis is what a need snapshot contributes to the search. A bank search
// has an empty basis.
type searchBasis struct {
specialization *domain.SpecializationCode
skills []requestedSkill
requestedFormats []domain.QuestionnaireWorkFormat
needDomainConfirmed bool
}
func loadBasis(ctx context.Context, unit outbound.UnitOfWork, request Request) (searchBasis, error) {
const location = "matching.loadBasis"
var needSkills, needDesired []domain.NeedSkill
basis := searchBasis{}
if request.Need != nil {
need, err := unit.Needs().GetVersion(ctx, request.OrganizationID, request.Need.NeedID, request.Need.RequirementsVersion)
if err != nil {
if errors.Is(err, outbound.ErrNeedNotFound) {
return searchBasis{}, ErrNeedNotFound
}
return searchBasis{}, fmt.Errorf("%s - read need snapshot: %w", location, err)
}
// A version that only edited a title or a suggestion is not a
// requirements snapshot of its own.
if need.RequirementsVersion() != request.Need.RequirementsVersion {
return searchBasis{}, ErrNeedNotFound
}
requirements := need.Snapshot().Requirements
if requirements.Specialization.Status == domain.NeedValueConfirmed && requirements.Specialization.Value != nil {
specialization := *requirements.Specialization.Value
basis.specialization = &specialization
}
if requirements.WorkFormats.Status == domain.NeedValueConfirmed && requirements.WorkFormats.Value != nil {
for _, format := range *requirements.WorkFormats.Value {
basis.requestedFormats = append(basis.requestedFormats, domain.QuestionnaireWorkFormat(format))
}
}
basis.needDomainConfirmed = requirements.Domain.Status == domain.NeedValueConfirmed
needSkills, needDesired = requirements.RequiredSkills, requirements.DesiredSkills
}
basis.skills = requestedSkills(needSkills, needDesired, request.Filters.Stack)
return basis, nil
}
// requestedSkills lists each distinct requested skill once. A confirmed
// required skill weighs more than a desired one, a stack filter tag counts as
// required, and a repeated code never counts twice, so repeating a skill in a
// need cannot raise or lower a score.
func requestedSkills(required, desired []domain.NeedSkill, stack []domain.CandidateViewSkillCode) []requestedSkill {
var skills []requestedSkill
byCode := make(map[string]int)
seenUnmapped := make(map[string]struct{})
add := func(code, name string, isRequired bool) {
if code == "" {
key := strings.ToLower(strings.TrimSpace(name))
if _, repeated := seenUnmapped[key]; repeated {
return
}
seenUnmapped[key] = struct{}{}
skills = append(skills, requestedSkill{required: isRequired})
return
}
if index, repeated := byCode[code]; repeated {
skills[index].required = skills[index].required || isRequired
return
}
byCode[code] = len(skills)
skills = append(skills, requestedSkill{code: code, required: isRequired})
}
for _, group := range []struct {
skills []domain.NeedSkill
isRequired bool
}{{required, true}, {desired, false}} {
for _, skill := range group.skills {
if skill.Status != domain.NeedItemConfirmed {
continue
}
code := ""
if skill.TaxonomyCode != nil {
code = *skill.TaxonomyCode
}
add(code, skill.Name, group.isRequired)
}
}
for _, tag := range stack {
add(string(tag), "", true)
}
return skills
}
// candidateEntry is one candidate specialization before scoring.
type candidateEntry struct {
candidateID uuid.UUID
card domain.AnonymousCandidateViewDTO
specialization domain.SpecializationCode
category *domain.CandidateViewCategory
declaredGrade *domain.GradeCode
}
// entriesOf derives the specializations that a card shows. A specialization is
// confirmed only when the card shows its category; one specialization never
// confirms another. A specialization that the self-assessment marks confirmed
// but whose category the card does not show is left out: a result cannot
// claim a confirmation that the candidate did not publish.
func entriesOf(visible domain.VisibleCandidateCard) []candidateEntry {
card := visible.Card
declared := make(map[domain.SpecializationCode]*domain.GradeCode, len(card.SelfAssessment))
for _, assessment := range card.SelfAssessment {
declared[assessment.Specialization] = assessment.DeclaredGrade
}
entries := make([]candidateEntry, 0, len(card.Categories)+len(card.SelfAssessment))
confirmed := make(map[domain.SpecializationCode]struct{}, len(card.Categories))
for index := range card.Categories {
category := card.Categories[index]
confirmed[category.Specialization] = struct{}{}
entries = append(entries, candidateEntry{
candidateID: visible.CandidateID, card: card, specialization: category.Specialization,
category: &category, declaredGrade: declared[category.Specialization],
})
}
for _, assessment := range card.SelfAssessment {
if _, isConfirmed := confirmed[assessment.Specialization]; isConfirmed ||
assessment.ConfirmationStatus != domain.CandidateViewConfirmationUnconfirmed {
continue
}
entries = append(entries, candidateEntry{
candidateID: visible.CandidateID, card: card, specialization: assessment.Specialization,
declaredGrade: assessment.DeclaredGrade,
})
}
return entries
}
// rankedEntry carries the sort keys next to the entry that leaves.
type rankedEntry struct {
entry Entry
candidate uuid.UUID
fit int64
coverage int64
rank int64
near bool
}
// groups holds the ranked entries of the three groups before the output is cut.
type groups struct {
main, near, unconfirmed []rankedEntry
}
func (service *Service) rank(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
basis searchBasis,
policy domain.MatchingPolicy,
cards []domain.VisibleCandidateCard,
) (groups, error) {
specialization, compatible := effectiveSpecialization(request.Filters.Specialization, basis.specialization)
if !compatible {
return groups{}, nil
}
requestedFormats := basis.requestedFormats
if conditions := request.Filters.Conditions; conditions != nil && len(conditions.WorkFormats) > 0 {
requestedFormats = conditions.WorkFormats
}
var accepted []candidateEntry
for _, visible := range cards {
for _, entry := range entriesOf(visible) {
if request.Filters.accepts(entry, specialization) {
accepted = append(accepted, entry)
}
}
}
reachedCohorts, err := service.reachedPercentileCohorts(ctx, unit, policy, accepted)
if err != nil {
return groups{}, err
}
facts, err := service.permittedFacts(ctx, unit, request, basis, accepted)
if err != nil {
return groups{}, err
}
var result groups
for _, entry := range accepted {
ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts)
switch {
case entry.category == nil:
result.unconfirmed = append(result.unconfirmed, ranked)
case ranked.near:
result.near = append(result.near, ranked)
default:
result.main = append(result.main, ranked)
}
}
slices.SortStableFunc(result.main, compareByRank)
slices.SortStableFunc(result.near, compareByRank)
slices.SortStableFunc(result.unconfirmed, compareByFit)
return result, nil
}
// reachedPercentileCohorts returns the categories among the accepted entries
// whose comparable real cohort has reached the policy minimum. The cohort of a
// category is the number of candidates who hold it from a source that is not a
// synthetic demonstration; only the categories of the accepted entries are
// counted. A percentile would need the theta of those members, which the
// organization-safe projection does not carry, so T stays the neutral value and
// the percentile stays null, but the reason is then "not computed" instead of
// "cohort below the minimum". The search never fails for it and logs one
// warning for each such category.
func (service *Service) reachedPercentileCohorts(
ctx context.Context,
unit outbound.UnitOfWork,
policy domain.MatchingPolicy,
accepted []candidateEntry,
) (map[outbound.CategoryKey]bool, error) {
seen := make(map[outbound.CategoryKey]struct{})
var categories []outbound.CategoryKey
for _, entry := range accepted {
if entry.category == nil {
continue
}
key := outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}
if _, repeated := seen[key]; !repeated {
seen[key] = struct{}{}
categories = append(categories, key)
}
}
counts, err := unit.Evidence().CountComparableRealCategories(ctx, categories)
if err != nil {
return nil, fmt.Errorf("matching.Service.reachedPercentileCohorts - count real cohorts: %w", err)
}
reached := make(map[outbound.CategoryKey]bool)
for _, key := range categories {
if counts[key] >= int64(policy.PercentileMinCohort) {
reached[key] = true
service.logger.WarnContext(ctx, "the real cohort of a category reached the percentile minimum, but the percentile is not computed",
slog.String("specialization", string(key.Specialization)),
slog.String("grade", string(key.Grade)),
slog.Int64("cohort_size", counts[key]),
slog.Int("minimum", int(policy.PercentileMinCohort)),
)
}
}
return reached, nil
}
// permittedFacts reads the permitted evidence of every candidate with a
// confirmed entry in one statement, and only when the request names skills.
func (service *Service) permittedFacts(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
basis searchBasis,
accepted []candidateEntry,
) (map[uuid.UUID][]evidenceSource, error) {
sources := make(map[uuid.UUID][]evidenceSource)
if len(basis.skills) == 0 {
return sources, nil
}
seen := make(map[uuid.UUID]struct{})
var requests []outbound.EvidenceCandidateCategories
for _, entry := range accepted {
if _, repeated := seen[entry.candidateID]; repeated || entry.category == nil {
continue
}
seen[entry.candidateID] = struct{}{}
requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: entry.candidateID, Categories: entry.card.Categories})
}
facts, err := unit.Evidence().ListOrganizationFactsBatch(ctx, request.OrganizationID, requests)
if err != nil {
return nil, fmt.Errorf("matching.Service.permittedFacts - read permitted evidence: %w", err)
}
for candidateID, candidateFacts := range facts {
sources[candidateID] = factSources(candidateFacts)
}
return sources, nil
}
// reveal cuts each group to the policy bound and charges the output in order.
func (service *Service) reveal(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
policy domain.MatchingPolicy,
ranked groups,
) (Result, error) {
result := Result{Source: sourceOf(request), Main: []Entry{}, Near: []Entry{}, Unconfirmed: []Entry{}}
limit := int(policy.MaxResultsPerGroup)
for _, group := range []*[]rankedEntry{&ranked.main, &ranked.near, &ranked.unconfirmed} {
if len(*group) > limit {
*group = (*group)[:limit]
result.Truncated = true
}
}
views, err := service.views(ctx, unit, request.ActorID, request.OrganizationID)
if err != nil {
return Result{}, fmt.Errorf("matching.Service.reveal - open card views: %w", err)
}
revealed := make(map[uuid.UUID]map[domain.CardField]struct{})
var order []uuid.UUID
charge := func(entries []rankedEntry) ([]Entry, bool, error) {
kept := make([]Entry, 0, len(entries))
for _, item := range entries {
if _, paid := revealed[item.candidate]; !paid {
allowed, err := views.Reserve(ctx, item.candidate)
if err != nil {
return nil, false, fmt.Errorf("matching.Service.reveal - reserve card view: %w", err)
}
if !allowed {
return kept, false, nil
}
revealed[item.candidate] = make(map[domain.CardField]struct{})
order = append(order, item.candidate)
}
for _, field := range entryFields(item.entry) {
revealed[item.candidate][field] = struct{}{}
}
kept = append(kept, item.entry)
}
return kept, true, nil
}
complete := true
for _, step := range []struct {
entries []rankedEntry
target *[]Entry
}{{ranked.main, &result.Main}, {ranked.near, &result.Near}, {ranked.unconfirmed, &result.Unconfirmed}} {
if !complete {
break
}
kept, ok, err := charge(step.entries)
if err != nil {
return Result{}, err
}
*step.target, complete = kept, ok
}
if !complete {
result.Truncated = true
}
for _, candidateID := range order {
if err := views.Record(ctx, candidateID, orderedFields(revealed[candidateID])); err != nil {
return Result{}, fmt.Errorf("matching.Service.reveal - record card view: %w", err)
}
}
return result, nil
}
// entryFields lists the card fields that an entry actually shows, so the
// candidate's history names what the search returned about them.
func entryFields(entry Entry) []domain.CardField {
var fields []domain.CardField
if entry.Category != nil {
fields = append(fields, domain.CardFieldCategories)
}
if len(entry.PublicContext.Stack) > 0 {
fields = append(fields, domain.CardFieldStack)
}
if entry.PublicContext.ExperienceBand != nil {
fields = append(fields, domain.CardFieldExperience)
}
// An unconfirmed entry exists only because the self-assessment is published.
if entry.Category == nil || entry.DeclaredGrade != nil {
fields = append(fields, domain.CardFieldSelfAssessment)
}
if len(entry.PublicContext.WorkFormats) > 0 {
fields = append(fields, domain.CardFieldWorkFormats)
}
if entry.PublicContext.SalaryCompatibility != nil {
fields = append(fields, domain.CardFieldSalaryCompatibility)
}
return fields
}
func orderedFields(set map[domain.CardField]struct{}) []domain.CardField {
fields := make([]domain.CardField, 0, len(set))
for _, field := range []domain.CardField{
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility,
} {
if _, shown := set[field]; shown {
fields = append(fields, field)
}
}
return fields
}
// effectiveSpecialization combines the filter with the specialization of the
// need. Two different specializations leave nothing to show.
func effectiveSpecialization(filter, need *domain.SpecializationCode) (*domain.SpecializationCode, bool) {
switch {
case filter != nil && need != nil && *filter != *need:
return nil, false
case filter != nil:
return filter, true
default:
return need, true
}
}
// factSources turns the permitted assessment facts into evidence. Each fact is
// the one measurement that supports a confirmed category, tagged with that
// category's specialization.
func factSources(facts []domain.EvidenceOrganizationFact) []evidenceSource {
sources := make([]evidenceSource, 0, len(facts))
for _, fact := range facts {
input := fact.Input()
sources = append(sources, evidenceSource{
code: string(input.Skill), trust: input.Trust, attribution: domain.EvidenceAttributionPersonal, measured: true,
})
}
return sources
}
func scoreEntry(
entry candidateEntry,
policy domain.MatchingPolicy,
basis searchBasis,
requestedFormats []domain.QuestionnaireWorkFormat,
facts []evidenceSource,
reachedCohorts map[outbound.CategoryKey]bool,
) rankedEntry {
evidence := make([]evidenceSource, 0, len(entry.card.Skills)+len(facts))
for _, skill := range entry.card.Skills {
evidence = append(evidence, evidenceSource{code: string(skill), trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal})
}
confirmed := entry.category != nil
if confirmed {
for _, fact := range facts {
// A fact supports only its own specialization's category.
if fact.code == string(entry.specialization) {
evidence = append(evidence, fact)
}
}
}
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence})
context := PublicContext{
ExperienceBand: entry.card.ExperienceBand, SalaryCompatibility: entry.card.SalaryCompatibility,
}
if len(entry.card.Skills) > 0 {
context.Stack = slices.Clone(entry.card.Skills)
}
if len(entry.card.WorkFormats) > 0 {
context.WorkFormats = slices.Clone(entry.card.WorkFormats)
}
summary, flags := explain(explanationInput{
confirmed: confirmed, declaredGrade: entry.declaredGrade, policy: policy, scores: computed, context: context,
requestedFormats: requestedFormats, needDomainConfirmed: basis.needDomainConfirmed,
percentileReason: percentileReason(entry, reachedCohorts),
})
components := Components{Fit: microToFloat(computed.fit), Coverage: microToFloat(computed.coverage)}
if confirmed {
components.Domain = microToFloat(computed.domain)
components.Semantics = microToFloat(computed.semantics)
components.Competition = microToFloat(computed.competition)
components.Freshness = microToFloat(computed.freshness)
components.Responsiveness = microToFloat(computed.responsive)
components.RankScore = microToFloat(computed.rank)
}
return rankedEntry{
entry: Entry{
CandidateHandle: entry.card.Pseudonym, Specialization: entry.specialization,
DeclaredGrade: entry.declaredGrade, Category: entry.category,
PublicContext: context, EvidenceSummary: summary, Components: components, UnknownFlags: flags,
},
candidate: entry.candidateID, fit: computed.fit, coverage: computed.coverage, rank: computed.rank,
near: confirmed && computed.belongsToNearGroup(policy),
}
}
// compareByRank orders a confirmed group: S descending, then coverage
// descending, then the internal identifier ascending. The identifier is the
// stable tie-breaker and never leaves the server; the specialization only
// separates two entries of the same candidate.
func compareByRank(left, right rankedEntry) int {
return cmp.Or(
cmp.Compare(right.rank, left.rank),
cmp.Compare(right.coverage, left.coverage),
slices.Compare(left.candidate[:], right.candidate[:]),
strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)),
)
}
// compareByFit orders the unconfirmed group: Fit descending, then coverage
// descending, then the internal identifier ascending. It never uses a
// confirmed-profile score.
func compareByFit(left, right rankedEntry) int {
return cmp.Or(
cmp.Compare(right.fit, left.fit),
cmp.Compare(right.coverage, left.coverage),
slices.Compare(left.candidate[:], right.candidate[:]),
strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)),
)
}
// sourceOf echoes the search basis. A bank search carries its normalized
// filters, so the result stays tied to what was asked.
func sourceOf(request Request) Source {
if request.Need != nil {
need := *request.Need
return Source{Need: &need}
}
filters := request.Filters
filters.Stack = slices.Clone(filters.Stack)
slices.Sort(filters.Stack)
if conditions := filters.Conditions; conditions != nil {
normalized := *conditions
normalized.WorkFormats = slices.Clone(conditions.WorkFormats)
slices.Sort(normalized.WorkFormats)
filters.Conditions = &normalized
}
return Source{Filters: filters}
}
// percentileReason says why the percentile of a confirmed entry is null.
func percentileReason(entry candidateEntry, reachedCohorts map[outbound.CategoryKey]bool) UnknownReason {
if entry.category != nil && reachedCohorts[outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}] {
return ReasonPercentileNotComputed
}
return ReasonCohortBelow30
}
+187
View File
@@ -0,0 +1,187 @@
package matching
import (
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrForbidden reports an actor that may not search: not a verified
// employer, or not the active owner of the organization.
ErrForbidden = errors.New("match search is forbidden")
// ErrNeedNotFound reports a need of another organization, an unknown need,
// or a requirements version that no confirmed-requirements change created.
ErrNeedNotFound = errors.New("match search need snapshot not found")
// ErrPolicyUnavailable reports an effective product policy without the
// matching section. The search fails closed instead of using defaults.
ErrPolicyUnavailable = errors.New("match search policy is unavailable")
// ErrServiceMissing reports an incomplete service wiring.
ErrServiceMissing = errors.New("match search service is unavailable")
)
// NeedReference selects one immutable confirmed-requirements snapshot.
type NeedReference struct {
NeedID uuid.UUID
RequirementsVersion int64
}
// GradeFilter is a confirmed category that a filter asks for.
type GradeFilter struct {
Specialization domain.SpecializationCode
Grade domain.GradeCode
}
// Conditions filter by the safe, coarse card conditions. An unknown card value
// never satisfies a condition.
type Conditions struct {
WorkFormats []domain.QuestionnaireWorkFormat
SalaryCompatibility *domain.CandidateViewSalaryCompatibility
}
// Filters narrow the organization-visible bank. A nil field is no filter.
type Filters struct {
Specialization *domain.SpecializationCode
ConfirmedGrade *domain.GradeCode
ConfirmedCategory *GradeFilter
ConfirmationStatus *domain.CandidateViewConfirmationStatus
DeclaredGrade *domain.GradeCode
Stack []domain.CandidateViewSkillCode
Conditions *Conditions
}
// Request is one search. The actor and the organization come from the
// authenticated session and the path, never from the body.
type Request struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
// Need selects a requirements snapshot. It is nil for a search of the
// whole organization-visible bank.
Need *NeedReference
Filters Filters
}
// Source is the search basis that the result carries.
type Source struct {
Need *NeedReference
// Filters are the normalized bank filters; they are set for a bank search.
Filters Filters
}
// EvidenceCode names a templated explanation item.
type EvidenceCode string
const (
EvidenceConfirmedCategory EvidenceCode = "confirmed_category"
EvidenceRequiredSkill EvidenceCode = "required_skill_evidence"
EvidenceDesiredSkill EvidenceCode = "desired_skill_evidence"
EvidenceWorkConditionsMatch EvidenceCode = "work_conditions_match"
EvidenceSalaryCompatibility EvidenceCode = "salary_compatibility"
EvidenceDeclaredGrade EvidenceCode = "declared_grade"
)
// EvidenceState is the verdict of one explanation item.
type EvidenceState string
const (
EvidenceStateSupports EvidenceState = "supports"
EvidenceStatePartial EvidenceState = "partial"
EvidenceStateGap EvidenceState = "gap"
EvidenceStateDeclaredOnly EvidenceState = "declared_only"
)
// EvidenceItem is one bounded explanation item without free text.
type EvidenceItem struct {
Code EvidenceCode
State EvidenceState
}
// UnknownComponent names a component whose value is unknown.
type UnknownComponent string
const (
UnknownSemantics UnknownComponent = "semantics"
UnknownPercentile UnknownComponent = "percentile"
UnknownAssessment UnknownComponent = "assessment"
UnknownFreshness UnknownComponent = "freshness"
UnknownResponsiveness UnknownComponent = "responsiveness"
UnknownExperienceBand UnknownComponent = "experience_band"
UnknownWorkFormats UnknownComponent = "work_formats"
UnknownSalaryCompatibility UnknownComponent = "salary_compatibility"
UnknownDomain UnknownComponent = "domain"
)
// UnknownReason is the bounded reason of an unknown component.
type UnknownReason string
const (
ReasonMLUnavailable UnknownReason = "ml_unavailable"
ReasonCohortBelow30 UnknownReason = "cohort_below_30"
ReasonNoConfirmationForSpecialization UnknownReason = "no_confirmation_for_specialization"
ReasonNotInPublicCard UnknownReason = "not_in_public_card"
ReasonNeedFieldUnconfirmed UnknownReason = "need_field_unconfirmed"
ReasonNoFreshnessHistory UnknownReason = "no_freshness_history"
ReasonNoResponseHistory UnknownReason = "no_response_history"
ReasonPercentileNotComputed UnknownReason = "percentile_not_computed"
)
// UnknownFlag reports one unavailable component and why.
type UnknownFlag struct {
Component UnknownComponent
Reason UnknownReason
}
// PublicContext is the safe part of the anonymous card that a result shows. A
// nil or empty value means the card does not show it.
type PublicContext struct {
Stack []domain.CandidateViewSkillCode
ExperienceBand *domain.CandidateExperienceBand
WorkFormats []domain.QuestionnaireWorkFormat
SalaryCompatibility *domain.CandidateViewSalaryCompatibility
}
// Components are the computed scores of an entry, each rounded to six
// decimals. An unconfirmed entry has only Fit and Coverage: it has no theta,
// T, P, percentile, or rank score.
type Components struct {
Fit float64
Coverage float64
Domain float64
Semantics float64
Competition float64
Freshness float64
Responsiveness float64
RankScore float64
// Percentile is nil while there are fewer comparable real candidates than
// the policy needs, and then T is the neutral value.
Percentile *float64
}
// Entry is one candidate specialization of a result. The handle is the
// organization-scoped pseudonym; no account or profile identifier leaves.
type Entry struct {
CandidateHandle string
Specialization domain.SpecializationCode
DeclaredGrade *domain.GradeCode
// Category and Strength are set only for a confirmed entry.
Category *domain.CandidateViewCategory
PublicContext PublicContext
EvidenceSummary []EvidenceItem
Components Components
UnknownFlags []UnknownFlag
}
// Result holds the three separate groups. Their scores are never merged into
// one scale.
type Result struct {
Source Source
Main []Entry
Near []Entry
Unconfirmed []Entry
// Truncated is true when the output is not the whole ranked bank: a group
// exceeded the policy bound, or the card-view allowance of the organization
// ended. It carries no count.
Truncated bool
}
+142 -86
View File
@@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
@@ -17,6 +17,13 @@ import (
var (
ErrInboxUnavailable = errors.New("notification inbox is unavailable")
// ErrInboxForbidden reports an account that may not use the requested
// cabinet inbox: a missing or unverified account, or an account of the
// other scenario.
ErrInboxForbidden = errors.New("notification inbox is forbidden")
// ErrInboxEmailNotVerified reports an employer account whose email is not
// confirmed; the organization operations answer it as email_not_verified.
ErrInboxEmailNotVerified = errors.New("notification inbox requires a confirmed email")
// ErrInboxContentUnavailable means the referenced source is missing or its
// current visibility no longer permits the original presentation.
ErrInboxContentUnavailable = errors.New("notification content is unavailable")
@@ -27,6 +34,12 @@ const (
maxInboxSummaryRunes = 500
)
// inboxLinkPathPattern is the shape of a content link: a same-origin
// absolute path of at most 256 characters from a narrow alphabet, so it has
// no query, fragment, escape, dot segment, or backslash. The public contract
// states the same pattern.
var inboxLinkPathPattern = regexp.MustCompile(`^/[A-Za-z0-9/_-]{0,255}$`)
// InboxContent is resolved from the current source at read time. It is never
// written to notification_inbox_events.
type InboxContent struct {
@@ -66,26 +79,15 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
}
func validInboxLinkPath(value string) bool {
if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") {
return false
}
parsed, err := url.ParseRequestURI(value)
if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value {
return false
}
for _, segment := range strings.Split(value, "/") {
if segment == "." || segment == ".." {
return false
}
}
return true
return inboxLinkPathPattern.MatchString(value) && !strings.HasPrefix(value, "//")
}
// InboxContentResolver reads the current source under its current visibility
// rules. It must return ErrInboxContentUnavailable when that source is gone or
// no longer safe to present.
// rules, inside the read transaction that also authorized the viewer. It must
// return ErrInboxContentUnavailable when that source is gone or no longer
// safe to present to the recipient.
type InboxContentResolver interface {
Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error)
Resolve(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
}
// InboxItem pairs immutable event metadata with content resolved for this
@@ -96,9 +98,11 @@ type InboxItem struct {
ContentUnavailable bool
}
// InboxListRequest is built from the authenticated recipient and optional
// organization context. The organization ID filters items but grants no
// authorization by itself.
// InboxListRequest is built from the authenticated recipient. A nil
// OrganizationID is the candidate cabinet: every organization that sent to
// the recipient. A set OrganizationID is the employer cabinet of that
// organization and requires the recipient's current active membership. The
// organization ID filters items but is never authorization by itself.
type InboxListRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
@@ -106,111 +110,163 @@ type InboxListRequest struct {
Limit int32
}
// InboxMarkReadRequest names one inbox item in the same cabinet scope as
// InboxListRequest.
type InboxMarkReadRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
EventID uuid.UUID
}
type InboxPage struct {
Items []InboxItem
HasMore bool
}
// InboxService coordinates recipient-scoped storage and read-time content
// resolution. A caller for employer-scoped notices must authorize current
// membership before constructing the request; invitation recipients need not
// belong to the sender's organization.
// InboxService lists and marks the inbox of the authenticated recipient.
// Every operation authorizes the recipient for the requested cabinet and
// reads the inbox in one transaction, so a membership revoked a moment ago
// cannot authorize a later read. The inbox stores references only: the text
// of an item is resolved from its current source at each list, so a hiding, a
// revoked membership, or a withdrawn source removes the content from every
// later read. Mail delivery is a separate concern: an item exists whether or
// not any email was sent, and an email failure never blocks it.
type InboxService struct {
repository outbound.NotificationInboxRepository
transactor outbound.Transactor
resolver InboxContentResolver
clock func() time.Time
}
func NewInboxService(
repository outbound.NotificationInboxRepository,
transactor outbound.Transactor,
resolver InboxContentResolver,
clock func() time.Time,
) (*InboxService, error) {
if repository == nil || resolver == nil || clock == nil {
return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable)
if transactor == nil || resolver == nil || clock == nil {
return nil, fmt.Errorf("notification.NewInboxService - transactor, resolver, and clock are required: %w", ErrInboxUnavailable)
}
return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil
return &InboxService{transactor: transactor, resolver: resolver, clock: clock}, nil
}
// StoreInvitationDelivered stores the recipient-specific reference to an
// invitation-delivered event. A transaction-bound repository lets a future
// event handler commit this row with the invitation state and consumer marker.
func (service *InboxService) StoreInvitationDelivered(
ctx context.Context,
input domain.NotificationInboxEntryInput,
) (bool, error) {
const location = "InboxService.StoreInvitationDelivered"
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
return false, err
}
created, err := service.repository.Store(ctx, entry)
if err != nil {
return false, fmt.Errorf("%s - store event: %w", location, err)
}
return created, nil
}
// List resolves each stored reference against its current source. A source
// that is missing or no longer visible is returned without source content.
// List returns one newest-first page and resolves each stored reference
// against its current source. A source that is missing or no longer visible
// is returned without content.
func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) {
const location = "InboxService.List"
if err := validateInboxListRequest(request); err != nil {
return InboxPage{}, err
}
stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{
RecipientUserID: request.RecipientUserID,
OrganizationID: request.OrganizationID,
After: request.After,
Limit: request.Limit,
var page InboxPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
return err
}
stored, err := unit.NotificationInbox().List(ctx, outbound.NotificationInboxListQuery{
RecipientUserID: request.RecipientUserID,
OrganizationID: request.OrganizationID,
After: request.After,
Limit: request.Limit,
})
if err != nil {
return fmt.Errorf("%s - list recipient events: %w", location, err)
}
resolved := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
for _, entry := range stored.Items {
if !inboxEntryMatchesRequest(entry, request) {
return fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, unit, entry)
switch {
case errors.Is(resolveErr, ErrInboxContentUnavailable):
item.ContentUnavailable = true
case resolveErr != nil:
return fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
default:
item.Content = &content
}
resolved.Items = append(resolved.Items, item)
}
page = resolved
return nil
})
if err != nil {
return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err)
}
page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
for _, entry := range stored.Items {
if !inboxEntryMatchesRequest(entry, request) {
return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, entry)
switch {
case errors.Is(resolveErr, ErrInboxContentUnavailable):
item.ContentUnavailable = true
case resolveErr != nil:
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
default:
item.Content = &content
}
page.Items = append(page.Items, item)
return InboxPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return page, nil
}
// MarkRead persists the first read timestamp for one recipient and exact
// organization context. The source is not read and no private content is
// returned by this command.
func (service *InboxService) MarkRead(
ctx context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
eventID uuid.UUID,
) (domain.NotificationInboxEntry, error) {
// MarkRead persists the first read timestamp of one item of the recipient. A
// repeat keeps the first timestamp. The source is not read and no content is
// returned. An item of another recipient, of another organization context,
// or an unknown item all return outbound.ErrNotificationInboxEntryNotFound.
func (service *InboxService) MarkRead(ctx context.Context, request InboxMarkReadRequest) (domain.NotificationInboxEntry, error) {
const location = "InboxService.MarkRead"
if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable)
if request.RecipientUserID == uuid.Nil || request.EventID == uuid.Nil ||
(request.OrganizationID != nil && *request.OrganizationID == uuid.Nil) {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient and event IDs are required: %w", location, ErrInboxUnavailable)
}
at := service.clock()
if at.IsZero() {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable)
}
entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at)
var entry domain.NotificationInboxEntry
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
return err
}
marked, err := unit.NotificationInbox().MarkRead(ctx, request.RecipientUserID, request.OrganizationID, request.EventID, at)
if err != nil {
return fmt.Errorf("%s - mark event read: %w", location, err)
}
entry = marked
return nil
})
if err != nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err)
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return entry, nil
}
// authorizeInboxViewer checks the account against the requested cabinet. The
// candidate cabinet needs a verified candidate account. The employer cabinet
// needs an employer account with a verified email (otherwise
// ErrInboxEmailNotVerified, like the other organization operations) and an
// active membership of any role in the named organization. The membership is
// locked FOR SHARE until the transaction ends, like the card reads, so a
// revocation cannot commit between this check and the read that follows. A
// missing or inactive membership returns outbound.ErrOrganizationNotFound, so
// an organization that exists cannot be told from one that does not.
func authorizeInboxViewer(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, organizationID *uuid.UUID) error {
const location = "notification.authorizeInboxViewer"
user, err := unit.Users().GetByID(ctx, userID)
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - account does not exist: %w", location, ErrInboxForbidden)
}
if err != nil {
return fmt.Errorf("%s - read account: %w", location, err)
}
if organizationID == nil {
if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() {
return fmt.Errorf("%s - the candidate inbox needs a verified candidate account: %w", location, ErrInboxForbidden)
}
return nil
}
if user.Scenario != domain.ScenarioEmployer {
return fmt.Errorf("%s - the organization inbox needs an employer account: %w", location, ErrInboxForbidden)
}
if !user.EmailVerified() {
return fmt.Errorf("%s - email is not verified: %w", location, ErrInboxEmailNotVerified)
}
if _, err := unit.Organizations().LockActiveMembership(ctx, *organizationID, userID); err != nil {
if errors.Is(err, outbound.ErrOrganizationNotFound) {
return fmt.Errorf("%s - no active membership: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
return nil
}
func validateInboxListRequest(request InboxListRequest) error {
const location = "notification.validateInboxListRequest"
if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize {
@@ -0,0 +1,82 @@
package notification
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// InboxSourceResolver resolves the content of the entries of one source
// type from the current state of that source, for the entry's recipient. It
// returns ErrInboxContentUnavailable when the source is gone or the recipient
// may not see it now.
type InboxSourceResolver func(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
// sourceContentResolver dispatches by source type. A source type without a
// resolver is unavailable, never guessed, so a new event type shows nothing
// until its resolver is registered.
type sourceContentResolver map[domain.NotificationInboxSourceType]InboxSourceResolver
var _ InboxContentResolver = sourceContentResolver(nil)
// NewInboxContentResolver combines the resolvers of the source types.
func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]InboxSourceResolver) InboxContentResolver {
return sourceContentResolver(resolvers)
}
// DefaultInboxSourceResolvers lists the source types that have a resolver
// today. The synthetic notice resolver is registered only when
// syntheticEnabled is true (development and browser-test stands); a stored
// synthetic row is then listed without content. The invitation module adds
// domain.NotificationInboxSourceInvitation with its own resolver; the
// handler, the table, and the API need no change.
func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver {
resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{}
if syntheticEnabled {
resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice
}
return resolvers
}
func (resolvers sourceContentResolver) Resolve(
ctx context.Context,
unit outbound.UnitOfWork,
entry domain.NotificationInboxEntry,
) (InboxContent, error) {
resolve, ok := resolvers[entry.SourceType()]
if !ok {
return InboxContent{}, ErrInboxContentUnavailable
}
return resolve(ctx, unit, entry)
}
const (
syntheticNoticeTitle = "Тестовое уведомление"
// syntheticNoticeSummary has one verb slot for the organization name.
syntheticNoticeSummary = "Организация «%s» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий."
)
// ResolveSyntheticNotice resolves a synthetic notice. The text is fixed and
// names the sending organization by its current name, which is read under the
// recipient's current standing: a candidate sees it until they hide the
// organization, an employer while they are an active member. Afterwards the
// entry stays in the list without content.
func ResolveSyntheticNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
const location = "notification.ResolveSyntheticNotice"
name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.SourceID())
if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) {
return InboxContent{}, ErrInboxContentUnavailable
}
if err != nil {
return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err)
}
content, err := NewInboxContent(syntheticNoticeTitle, fmt.Sprintf(syntheticNoticeSummary, name), "")
if err != nil {
// A stored name that does not fit the presentation is not shown.
return InboxContent{}, ErrInboxContentUnavailable
}
return content, nil
}
@@ -0,0 +1,213 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// InboxConsumerName names the consumer group and scopes deduplication of the
// inbox handler. Renaming it makes the consumer process every retained event
// again; the inbox key keeps the rows unique, but do not rename it lightly.
const InboxConsumerName = "notification_inbox"
// inboxPayloadSchemaVersion is the only supported schema version of the
// inbox events. Version 1 is inboxEventPayload.
const inboxPayloadSchemaVersion = 1
// inboxEventPayload is version 1 of the payload of every event the inbox
// stores. It names the recipient and the organization context and nothing
// else: the text is resolved from the source when the inbox is read, so
// neither the outbox nor the event bus keeps content that could outlive a
// revocation.
type inboxEventPayload struct {
RecipientUserID uuid.UUID `json:"recipient_user_id"`
OrganizationID uuid.UUID `json:"organization_id"`
}
// inboxProjection describes how one event type becomes an inbox row: the
// aggregate the event must come from and where the content source is.
type inboxProjection struct {
aggregateType string
// source returns the source record of the content for a decoded event.
source func(event outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID
}
// inboxProjections is the allowlist of events the inbox stores. A producer
// plugs in by appending an event of one of these types in its own
// transaction; adding a type here also needs the same pair in
// domain.NotificationInboxSourceFor, the CHECK constraint of the table, and a
// content resolver for its source type.
//
// - invitation.delivered: the aggregate is the invitation, which is also
// the source. Invitations are a later module; the projection and the
// payload contract are fixed here so that it needs no inbox change.
// - notification.synthetic_delivered: a synthetic event for tests and
// probes. Its aggregate is a one-off notice and its source is the
// organization of the payload.
var inboxProjections = map[domain.NotificationInboxEventType]inboxProjection{
domain.NotificationInboxInvitationDelivered: {
aggregateType: "invitation",
source: func(event outbound.ConsumedEvent, _ inboxEventPayload) uuid.UUID {
return event.AggregateID
},
},
domain.NotificationInboxSyntheticDelivered: {
aggregateType: SyntheticNoticeAggregateType,
source: func(_ outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID {
return payload.OrganizationID
},
},
}
// SyntheticNoticeAggregateType is the aggregate type of a synthetic inbox
// event. Every notice is its own aggregate at version 1.
const SyntheticNoticeAggregateType = "synthetic_notice"
// SyntheticNoticeAggregateVersion is the version of a synthetic notice.
const SyntheticNoticeAggregateVersion = 1
// SyntheticNoticeEventPayload builds the version 1 payload of a synthetic
// inbox event for the outbox. It is the single writer of the contract that
// the inbox handler reads.
func SyntheticNoticeEventPayload(recipientUserID, organizationID uuid.UUID) ([]byte, error) {
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: recipientUserID, OrganizationID: organizationID})
if err != nil {
return nil, fmt.Errorf("notification.SyntheticNoticeEventPayload - encode payload: %w", err)
}
return payload, nil
}
// InboxHandler stores one inbox row for each inbox event, in the consumer
// transaction that records the event as processed. The row key is the
// recipient and the event ID, so a repeated delivery, a replayed dead letter,
// or a renamed consumer still stores one row, and a redelivery that changed
// the immutable metadata is refused instead of overwritten.
//
// The inbox is the in-platform delivery state of a notification: a stored row
// means delivered. Nothing here reads mail state, so an unverified address, a
// missing mail provider, or a failed email never blocks a notification.
type InboxHandler struct {
logger *slog.Logger
syntheticEnabled bool
}
var _ inbound.EventHandler = (*InboxHandler)(nil)
// NewInboxHandler creates the handler. The synthetic event type is handled
// only when syntheticEnabled is true, which a development or browser-test
// stand sets; otherwise such an event is acknowledged and ignored.
func NewInboxHandler(logger *slog.Logger, syntheticEnabled bool) *InboxHandler {
return &InboxHandler{logger: logger, syntheticEnabled: syntheticEnabled}
}
func (*InboxHandler) ConsumerName() string { return InboxConsumerName }
func (handler *InboxHandler) Handles(eventType string) bool {
return handler.handles(domain.NotificationInboxEventType(eventType))
}
func (handler *InboxHandler) handles(eventType domain.NotificationInboxEventType) bool {
if eventType == domain.NotificationInboxSyntheticDelivered && !handler.syntheticEnabled {
return false
}
_, known := inboxProjections[eventType]
return known
}
// Handle turns the event into an inbox row:
//
// - A payload or envelope that breaks the contract, a recipient or
// organization that does not exist, or an event ID that already holds
// different metadata is rejected for good (inbound.ErrEventRejected).
// - A recipient account that was deleted is skipped: its private inbox
// went with it. An account deleted between the check and the insert
// aborts the insert; the error is returned for a retry, and the retry
// finds the account gone and skips.
// - Storage errors, including a recipient that disappeared, are returned
// for a retry.
//
// Errors and logs carry event IDs, never the payload.
func (handler *InboxHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
const location = "InboxHandler.Handle"
eventType := domain.NotificationInboxEventType(event.EventType)
projection := inboxProjections[eventType]
if !handler.handles(eventType) {
return fmt.Errorf("%s - event type is not an inbox event: %w", location, inbound.ErrEventRejected)
}
payload, err := decodeInboxPayload(event, projection)
if err != nil {
return err
}
if _, err := unit.Users().GetByID(ctx, payload.RecipientUserID); err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
handler.logger.InfoContext(ctx, "inbox event skipped because the recipient account does not exist",
slog.String("event_id", event.EventID.String()))
return nil
}
return fmt.Errorf("%s - read recipient account: %w", location, err)
}
sourceType, _ := domain.NotificationInboxSourceFor(eventType)
entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: event.EventID,
RecipientUserID: payload.RecipientUserID,
OrganizationID: payload.OrganizationID,
EventType: eventType,
SchemaVersion: event.SchemaVersion,
SourceType: sourceType,
SourceID: projection.source(event, payload),
OccurredAt: event.OccurredAt,
})
if err != nil {
return fmt.Errorf("%s - build inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
}
if _, err := unit.NotificationInbox().Store(ctx, entry); err != nil {
// A vanished recipient (ErrNotificationInboxRecipientMissing) is not
// the event's fault: it is retried and then skipped above.
if errors.Is(err, outbound.ErrNotificationInboxEventConflict) || errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) {
return fmt.Errorf("%s - store inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
}
return fmt.Errorf("%s - store inbox entry: %w", location, err)
}
return nil
}
// decodeInboxPayload checks the envelope and the version 1 payload. Errors
// name the broken rule and never quote the payload.
func decodeInboxPayload(event outbound.ConsumedEvent, projection inboxProjection) (inboxEventPayload, error) {
const location = "notification.decodeInboxPayload"
rejected := func(reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
}
if event.SchemaVersion != inboxPayloadSchemaVersion {
return inboxEventPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
}
if event.AggregateType != projection.aggregateType || event.AggregateID == uuid.Nil {
return inboxEventPayload{}, rejected("aggregate does not match the event type")
}
var payload inboxEventPayload
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
decoder.DisallowUnknownFields()
// The decoder error can quote a fragment of the payload, so it is not
// wrapped. A second value after the object is refused as well.
if err := decoder.Decode(&payload); err != nil {
return inboxEventPayload{}, rejected("payload is not a valid inbox event")
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return inboxEventPayload{}, rejected("payload has data after the inbox event")
}
if payload.RecipientUserID == uuid.Nil || payload.OrganizationID == uuid.Nil {
return inboxEventPayload{}, rejected("recipient and organization IDs are required")
}
return payload, nil
}
@@ -0,0 +1,201 @@
package notification
import (
"context"
"encoding/json"
"errors"
"log/slog"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
func newInboxHandlerFixture(t *testing.T) (*InboxHandler, *inboxFixture, outbound.ConsumedEvent) {
t.Helper()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
payload, err := SyntheticNoticeEventPayload(fixture.user.ID, fixture.organizationID)
if err != nil {
t.Fatalf("SyntheticNoticeEventPayload() error = %v", err)
}
event := outbound.ConsumedEvent{
EventID: uuid.New(), EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1,
AggregateType: SyntheticNoticeAggregateType, AggregateID: uuid.New(), AggregateVersion: SyntheticNoticeAggregateVersion,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
}
return NewInboxHandler(slog.New(slog.DiscardHandler), true), fixture, event
}
func TestInboxHandlerStoresOneRowForARepeatedEvent(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
if !handler.Handles(event.EventType) || handler.Handles("notification.mail_requested") {
t.Fatal("Handles() must accept inbox events only")
}
for range 2 {
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
}
if len(fixture.repository.entries) != 1 {
t.Fatalf("stored rows = %d, want one for a repeated event ID", len(fixture.repository.entries))
}
entry := fixture.repository.entries[0]
if entry.EventID() != event.EventID || entry.RecipientUserID() != fixture.user.ID ||
entry.OrganizationID() != fixture.organizationID || entry.SourceID() != fixture.organizationID ||
entry.SourceType() != domain.NotificationInboxSourceOrganization {
t.Fatalf("stored entry = %+v, want the references of the event", entry)
}
if _, isRead := entry.ReadAt(); isRead {
t.Fatal("a delivered row starts as read")
}
}
func TestInboxHandlerRejectsEventsThatBreakTheContract(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
mutate func(*outbound.ConsumedEvent, *inboxFixture)
}{
{name: "schema version", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.SchemaVersion = 2 }},
{name: "aggregate type", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.AggregateType = "mail_request" }},
{name: "unknown field", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `","organization_id":"` + fixture.organizationID.String() + `","email":"a@example.test"}`)
}},
{name: "missing organization", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `"}`)
}},
{name: "not an object", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.Payload = json.RawMessage(`[]`) }},
{name: "trailing data", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) {
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {}`)...)
}},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
test.mutate(&event, fixture)
err := handler.Handle(context.Background(), fixture.unit(), event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
}
if len(fixture.repository.entries) != 0 {
t.Fatal("a rejected event stored a row")
}
})
}
}
func TestInboxHandlerRejectsAnEventIDReusedWithOtherMetadata(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(first) error = %v", err)
}
event.OccurredAt = event.OccurredAt.Add(time.Hour)
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(changed replay) error = %v, want ErrEventRejected", err)
}
}
func TestInboxHandlerSkipsADeletedRecipientAndKeepsStoreErrorsRetryable(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
delete(fixture.users, fixture.user.ID)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(deleted recipient) error = %v, want a skip", err)
}
if len(fixture.repository.entries) != 0 {
t.Fatal("a deleted recipient got a row")
}
handler, fixture, event = newInboxHandlerFixture(t)
fixture.repository.storeErr = errors.New("connection reset")
err := handler.Handle(context.Background(), fixture.unit(), event)
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(store failure) error = %v, want a retryable error", err)
}
fixture.repository.storeErr = outbound.ErrNotificationInboxReferenceMissing
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(missing organization) error = %v, want ErrEventRejected", err)
}
// A recipient deleted between the check and the insert is not the event's
// fault: the attempt is retried, and the retry skips the deleted account.
fixture.repository.storeErr = outbound.ErrNotificationInboxRecipientMissing
if err := handler.Handle(context.Background(), fixture.unit(), event); err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(vanished recipient) error = %v, want a retryable error", err)
}
delete(fixture.users, fixture.user.ID)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(retry after the recipient vanished) error = %v, want a skip", err)
}
}
func TestInboxHandlerPlugsInInvitationEventsWithTheSameContract(t *testing.T) {
t.Parallel()
handler, fixture, _ := newInboxHandlerFixture(t)
invitationID := uuid.New()
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID})
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
event := outbound.ConsumedEvent{
EventID: uuid.New(), EventType: string(domain.NotificationInboxInvitationDelivered), SchemaVersion: 1,
AggregateType: "invitation", AggregateID: invitationID, AggregateVersion: 3,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
}
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(invitation.delivered) error = %v", err)
}
entry := fixture.repository.entries[0]
if entry.SourceType() != domain.NotificationInboxSourceInvitation || entry.SourceID() != invitationID {
t.Fatalf("invitation entry source = %s %s, want the invitation aggregate", entry.SourceType(), entry.SourceID())
}
}
func TestInboxHandlerStoresARowWhateverTheStateOfTheAddress(t *testing.T) {
t.Parallel()
// A mail delivery skips an address that is not verified. The inbox is the
// delivery state inside the platform and reads no mail state.
handler, fixture, event := newInboxHandlerFixture(t)
unverified := fixture.user
unverified.EmailVerifiedAt = nil
fixture.users[unverified.ID] = unverified
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(unverified address) error = %v", err)
}
if len(fixture.repository.entries) != 1 {
t.Fatalf("stored rows = %d, want 1: an address state must not block a notification", len(fixture.repository.entries))
}
}
func TestInboxHandlerIgnoresTheSyntheticEventWhileItIsSwitchedOff(t *testing.T) {
t.Parallel()
_, fixture, event := newInboxHandlerFixture(t)
off := NewInboxHandler(slog.New(slog.DiscardHandler), false)
if off.Handles(event.EventType) {
t.Fatal("the synthetic event is handled while the switch is off")
}
if !off.Handles(string(domain.NotificationInboxInvitationDelivered)) {
t.Fatal("the invitation event must not depend on the synthetic switch")
}
if err := off.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) || len(fixture.repository.entries) != 0 {
t.Fatalf("Handle(synthetic, off) error = %v, rows = %d, want a rejection and no row", err, len(fixture.repository.entries))
}
if _, ok := DefaultInboxSourceResolvers(false)[domain.NotificationInboxSourceOrganization]; ok {
t.Fatal("the synthetic resolver is registered while the switch is off")
}
if _, ok := DefaultInboxSourceResolvers(true)[domain.NotificationInboxSourceOrganization]; !ok {
t.Fatal("the synthetic resolver is missing while the switch is on")
}
}
@@ -3,6 +3,7 @@ package notification
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -12,78 +13,168 @@ import (
"lincodex/backend/internal/port/outbound"
)
func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) {
t.Parallel()
repository := &memoryInboxRepository{}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
input := inboxTestEntryInput()
created, err := service.StoreInvitationDelivered(context.Background(), input)
if err != nil || !created {
t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err)
}
created, err = service.StoreInvitationDelivered(context.Background(), input)
if err != nil || created {
t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err)
}
if len(repository.entries) != 1 {
t.Fatalf("stored entries = %d, want one", len(repository.entries))
}
changed := input
changed.SourceID = uuid.New()
if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) {
t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err)
}
}
func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) {
t.Parallel()
first := mustInboxTestEntry(t, inboxTestEntryInput())
secondInput := inboxTestEntryInput()
secondInput.RecipientUserID = first.RecipientUserID()
secondInput.OrganizationID = first.OrganizationID()
secondInput.EventID = uuid.New()
second := mustInboxTestEntry(t, secondInput)
wrongOrganizationInput := inboxTestEntryInput()
wrongOrganizationInput.RecipientUserID = first.RecipientUserID()
wrongOrganizationInput.EventID = uuid.New()
wrongOrganizationInput.OrganizationID = uuid.New()
wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput)
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}}
resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}}
service := newInboxTestService(t, repository, resolver, time.Now)
orgID := first.OrganizationID()
page, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10,
})
fixture := newInboxFixture(t, domain.ScenarioCandidate)
first := fixture.add(t, fixture.entryInput())
second := fixture.add(t, fixture.entryInput())
fixture.resolver.unavailable[second.EventID()] = true
otherRecipient := fixtureEntryInput(uuid.New(), fixture.organizationID)
fixture.add(t, otherRecipient)
page, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if err != nil {
t.Fatalf("List() error = %v", err)
}
if len(page.Items) != 2 {
t.Fatalf("List() returned %d items, want 2", len(page.Items))
t.Fatalf("List() returned %d items, want only the recipient's 2", len(page.Items))
}
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", page.Items[0])
byID := map[uuid.UUID]InboxItem{}
for _, item := range page.Items {
byID[item.Entry.EventID()] = item
}
if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1])
if item := byID[first.EventID()]; item.Content == nil || item.ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", item)
}
if resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
if item := byID[second.EventID()]; item.Content != nil || !item.ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", item)
}
if fixture.resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", fixture.resolver.calls)
}
}
func TestInboxServiceAuthorizesTheCabinetInTheReadTransaction(t *testing.T) {
t.Parallel()
t.Run("the candidate inbox refuses an employer", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(employer in the candidate cabinet) error = %v, want ErrInboxForbidden", err)
}
if fixture.repository.listCalls != 0 {
t.Fatal("the repository was read before the account was authorized")
}
})
t.Run("the organization inbox refuses a candidate", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
_, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(candidate in the organization cabinet) error = %v, want ErrInboxForbidden", err)
}
})
t.Run("an unknown or unverified account is refused", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: uuid.New(), Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(unknown account) error = %v, want ErrInboxForbidden", err)
}
fixture.user.EmailVerifiedAt = nil
fixture.users[fixture.user.ID] = fixture.user
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(unverified account) error = %v, want ErrInboxForbidden", err)
}
})
t.Run("a revoked membership answers like an unknown organization", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
entry := fixture.add(t, fixture.entryInput())
request := InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10}
page, err := fixture.service.List(context.Background(), request)
if err != nil || len(page.Items) != 1 {
t.Fatalf("List(active member) = %d items, %v, want 1 item", len(page.Items), err)
}
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateRemoved)
if _, err := fixture.service.List(context.Background(), request); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("List(revoked member) error = %v, want ErrOrganizationNotFound", err)
}
_, err = fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: entry.EventID(),
})
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("MarkRead(revoked member) error = %v, want ErrOrganizationNotFound", err)
}
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
t.Fatal("a revoked member marked an item read")
}
unknown := uuid.New()
_, err = fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &unknown, Limit: 10})
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("List(unknown organization) error = %v, want the same ErrOrganizationNotFound", err)
}
})
}
func TestInboxServiceOrganizationCabinetServesEveryRoleItsOwnItems(t *testing.T) {
t.Parallel()
for _, role := range []domain.OrganizationRole{
domain.OrganizationRoleOwner, domain.OrganizationRoleRecruiter,
domain.OrganizationRoleHiringManager, domain.OrganizationRoleTechnicalExpert,
} {
t.Run(string(role), func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, role, domain.MembershipStateActive)
own := fixture.add(t, fixture.entryInput())
otherMember := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
otherOrganization := fixture.add(t, fixtureEntryInput(fixture.user.ID, uuid.New()))
page, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if err != nil || len(page.Items) != 1 || page.Items[0].Entry.EventID() != own.EventID() {
t.Fatalf("List(%s) = %d items, %v, want only its own item", role, len(page.Items), err)
}
if fixture.locks == 0 {
t.Fatal("the membership was not locked for the read")
}
for _, foreign := range []domain.NotificationInboxEntry{otherMember, otherOrganization} {
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: foreign.EventID(),
})
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
t.Fatalf("MarkRead(%s, foreign item) error = %v, want ErrNotificationInboxEntryNotFound", role, err)
}
}
if _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: own.EventID(),
}); err != nil {
t.Fatalf("MarkRead(%s, own item) error = %v", role, err)
}
})
}
}
func TestInboxServiceOrganizationCabinetNeedsAConfirmedEmail(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
fixture.user.EmailVerifiedAt = nil
fixture.users[fixture.user.ID] = fixture.user
_, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if !errors.Is(err, ErrInboxEmailNotVerified) {
t.Fatalf("List(unverified employer) error = %v, want ErrInboxEmailNotVerified", err)
}
}
func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
_, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10,
})
fixture := newInboxFixture(t, domain.ScenarioCandidate)
fixture.repository.ignoreListScope = true
fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
}
@@ -92,21 +183,17 @@ func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T
func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC)
secondRead := firstRead.Add(time.Hour)
clockCalls := 0
clock := func() time.Time {
fixture := newInboxFixtureWithClock(t, domain.ScenarioCandidate, func() time.Time {
clockCalls++
if clockCalls == 1 {
return firstRead
}
return secondRead
}
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
return firstRead.Add(time.Duration(clockCalls-1) * time.Hour)
})
entry := fixture.add(t, fixture.entryInput())
for range 2 {
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
read, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, EventID: entry.EventID(),
})
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
@@ -117,6 +204,22 @@ func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
}
}
func TestInboxServiceMarkReadRefusesAnotherRecipientsItem(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
foreign := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, EventID: foreign.EventID(),
})
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
t.Fatalf("MarkRead(foreign item) error = %v, want ErrNotificationInboxEntryNotFound", err)
}
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
t.Fatal("another recipient's item was marked read")
}
}
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
t.Parallel()
@@ -129,6 +232,9 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
{name: "query string", path: "/candidate/invitations?token=secret"},
{name: "fragment", path: "/candidate/invitations#current"},
{name: "backslash", path: `/candidate\\invitations`},
{name: "escape", path: "/candidate/%2e%2e/invitations"},
{name: "dot segment", path: "/candidate/../invitations"},
{name: "too long", path: "/" + strings.Repeat("a", 300)},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -138,32 +244,112 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
}
})
}
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"); err != nil {
t.Fatalf("NewInboxContent(same-origin path) error = %v", err)
}
}
func newInboxTestService(
t *testing.T,
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) *InboxService {
func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
entry := fixture.add(t, fixture.entryInput())
unit := fixture.unit()
content, err := ResolveSyntheticNotice(context.Background(), unit, entry)
if err != nil {
t.Fatalf("ResolveSyntheticNotice(visible) error = %v", err)
}
if content.Title() != syntheticNoticeTitle || content.LinkPath() != "" || content.Summary() == "" {
t.Fatalf("synthetic content = %+v", content)
}
fixture.repository.organizationName = ""
if _, err := ResolveSyntheticNotice(context.Background(), unit, entry); !errors.Is(err, ErrInboxContentUnavailable) {
t.Fatalf("ResolveSyntheticNotice(not visible) error = %v, want ErrInboxContentUnavailable", err)
}
resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(true))
invitation := fixtureEntry(t, domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID,
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
})
if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) {
t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err)
}
}
type inboxFixture struct {
service *InboxService
repository *memoryInboxRepository
resolver *memoryInboxResolver
users map[uuid.UUID]domain.User
memberships map[uuid.UUID]domain.Membership
user domain.User
organizationID uuid.UUID
locks int
}
func newInboxFixture(t *testing.T, scenario domain.Scenario) *inboxFixture {
t.Helper()
service, err := NewInboxService(repository, resolver, clock)
return newInboxFixtureWithClock(t, scenario, time.Now)
}
func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func() time.Time) *inboxFixture {
t.Helper()
verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
fixture := &inboxFixture{
repository: &memoryInboxRepository{organizationName: "Север"},
resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}},
users: map[uuid.UUID]domain.User{},
memberships: map[uuid.UUID]domain.Membership{},
user: domain.User{ID: uuid.New(), Scenario: scenario, EmailVerifiedAt: &verifiedAt},
organizationID: uuid.New(),
}
fixture.users[fixture.user.ID] = fixture.user
service, err := NewInboxService(inboxTestTransactor{fixture: fixture}, fixture.resolver, clock)
if err != nil {
t.Fatalf("NewInboxService() error = %v", err)
}
return service
fixture.service = service
return fixture
}
func inboxTestEntryInput() domain.NotificationInboxEntryInput {
func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} }
func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput {
return fixtureEntryInput(fixture.user.ID, fixture.organizationID)
}
func (fixture *inboxFixture) add(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry := fixtureEntry(t, input)
fixture.repository.entries = append(fixture.repository.entries, entry)
return entry
}
func (fixture *inboxFixture) addMembership(t *testing.T, role domain.OrganizationRole, state domain.MembershipState) {
t.Helper()
now := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: uuid.New(), OrganizationID: fixture.organizationID, UserID: fixture.user.ID,
Role: string(role), State: string(state), CreatedAt: now, UpdatedAt: now,
})
if err != nil {
t.Fatalf("RestoreMembership() error = %v", err)
}
fixture.memberships[fixture.user.ID] = membership
}
func fixtureEntryInput(recipientID, organizationID uuid.UUID) domain.NotificationInboxEntryInput {
return domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID,
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
}
}
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
func fixtureEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
@@ -172,14 +358,71 @@ func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput)
return entry
}
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
type inboxTestTransactor struct{ fixture *inboxFixture }
func (transactor inboxTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
return fn(ctx, transactor.fixture.unit())
}
type inboxTestUnit struct {
outbound.UnitOfWork
fixture *inboxFixture
}
func (unit inboxTestUnit) Users() outbound.UserRepository {
return inboxTestUsers{fixture: unit.fixture}
}
func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository {
return inboxTestOrganizations{fixture: unit.fixture}
}
func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository {
return unit.fixture.repository
}
type inboxTestUsers struct {
outbound.UserRepository
fixture *inboxFixture
}
func (repository inboxTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
user, ok := repository.fixture.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type inboxTestOrganizations struct {
outbound.OrganizationRepository
fixture *inboxFixture
}
// LockActiveMembership answers like the real repository: only an active
// membership of the account in the organization is returned.
func (repository inboxTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
repository.fixture.locks++
membership, ok := repository.fixture.memberships[userID]
if !ok || membership.OrganizationID() != organizationID || !membership.GrantsAccess() {
return domain.Membership{}, outbound.ErrOrganizationNotFound
}
return membership, nil
}
type memoryInboxRepository struct {
entries []domain.NotificationInboxEntry
ignoreListScope bool
entries []domain.NotificationInboxEntry
ignoreListScope bool
listCalls int
organizationName string
storeErr error
}
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
if repository.storeErr != nil {
return false, repository.storeErr
}
for _, existing := range repository.entries {
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
continue
@@ -194,6 +437,7 @@ func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.N
}
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
repository.listCalls++
page := outbound.NotificationInboxPage{}
for _, entry := range repository.entries {
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
@@ -207,12 +451,13 @@ func (repository *memoryInboxRepository) List(_ context.Context, query outbound.
func (repository *memoryInboxRepository) MarkRead(
_ context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error) {
for index, entry := range repository.entries {
if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID {
if entry.RecipientUserID() != recipientUserID || entry.EventID() != eventID ||
(organizationID != nil && entry.OrganizationID() != *organizationID) {
continue
}
read, err := entry.MarkRead(at)
@@ -225,6 +470,13 @@ func (repository *memoryInboxRepository) MarkRead(
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
}
func (repository *memoryInboxRepository) OrganizationNameForRecipient(context.Context, uuid.UUID, uuid.UUID) (string, error) {
if repository.organizationName == "" {
return "", outbound.ErrNotificationInboxSourceNotVisible
}
return repository.organizationName, nil
}
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
@@ -236,7 +488,7 @@ type memoryInboxResolver struct {
calls int
}
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
func (resolver *memoryInboxResolver) Resolve(_ context.Context, _ outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
resolver.calls++
if resolver.unavailable[entry.EventID()] {
return InboxContent{}, ErrInboxContentUnavailable
@@ -0,0 +1,74 @@
package policy
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ErrNotDemoPolicy reports a latest product policy that is not a demonstration
// version. The operator command never builds on a calibrated version.
var ErrNotDemoPolicy = errors.New("the latest product policy is not a demonstration version")
// ErrPolicyChanged reports that another publication took the next version
// number while the section was being added. Nothing was stored; the command
// can be run again.
var ErrPolicyChanged = errors.New("the product policy changed during publication, run the command again")
// MatchingResult reports what EnsureDemoMatchingSection did. Version is the
// version that carries the matching section: the new one when Created, the
// latest one otherwise.
type MatchingResult struct {
Created bool
Version domain.PolicyVersion
}
// EnsureDemoMatchingSection makes the latest demonstration version carry the
// demo matching section. A version that already has the section is left alone.
// Otherwise it publishes the next version: a copy of the latest one with
// domain.DemoMatchingPolicy added, so no other value changes. It refuses a
// latest version that is not a demonstration version and a family without a
// version, because the section is only an addition to a policy that exists.
func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
const location = "Publisher.EnsureDemoMatchingSection"
latest, err := publisher.policies.GetLatest(ctx, domain.ProductPolicyKey)
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return MatchingResult{}, fmt.Errorf("%s - the product policy has no version to extend: %w", location, err)
}
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - read latest version: %w", location, err)
}
current := latest.Policy()
if current.Matching != nil {
return MatchingResult{Version: latest}, nil
}
if latest.Kind() != domain.PolicyKindDemo {
return MatchingResult{}, fmt.Errorf("%s - latest version %d is %s: %w", location, latest.Version(), latest.Kind(), ErrNotDemoPolicy)
}
matching := domain.DemoMatchingPolicy()
current.Matching = &matching
// The new version is built on the version that was read, so it takes the
// next number exactly once. A taken number means the base is no longer the
// latest, and the operator decides again instead of the command retrying.
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: current,
})
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - build the extended version: %w", location, err)
}
numbered, err := draft.WithVersion(latest.Version() + 1)
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - number the extended version: %w", location, err)
}
published, err := publisher.policies.Create(ctx, numbered)
if errors.Is(err, outbound.ErrPolicyVersionConflict) {
return MatchingResult{}, fmt.Errorf("%s - version %d is taken: %w", location, numbered.Version(), ErrPolicyChanged)
}
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - store the extended version: %w", location, err)
}
return MatchingResult{Created: true, Version: published}, nil
}
@@ -0,0 +1,83 @@
package policy
import (
"context"
"errors"
"testing"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func seedVersion(t *testing.T, store *memoryPolicies, kind domain.PolicyKind, product domain.ProductPolicy) {
t.Helper()
publisher := NewPublisher(store, testClock)
if _, err := publisher.Publish(context.Background(), PublishInput{
Key: domain.ProductPolicyKey, Kind: kind, Author: domain.DemoPolicySeedAuthor, Policy: product,
}); err != nil {
t.Fatalf("Publish() error = %v", err)
}
}
func TestEnsureDemoMatchingSectionAddsOnlyTheSection(t *testing.T) {
store := &memoryPolicies{}
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2())
publisher := NewPublisher(store, testClock)
result, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night")
if err != nil || !result.Created || result.Version.Version() != 2 {
t.Fatalf("EnsureDemoMatchingSection() = %+v, %v, want version 2 created", result, err)
}
extended := result.Version.Policy()
want := domain.DemoProductPolicyV2()
if extended.Matching == nil || extended.Support == nil || extended.Assessment.Attempt == nil ||
extended.Invitations.MaxPendingPerNeed != want.Invitations.MaxPendingPerNeed {
t.Fatalf("extended policy = %+v, want the earlier sections kept and the matching section added", extended)
}
if result.Version.Kind() != domain.PolicyKindDemo || string(result.Version.Author()) != "operator:night" {
t.Fatalf("version kind/author = %s/%s", result.Version.Kind(), result.Version.Author())
}
again, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night")
if err != nil || again.Created || again.Version.Version() != 2 || len(store.versions) != 2 {
t.Fatalf("second call = %+v, %v with %d versions, want no new version", again, err, len(store.versions))
}
}
func TestEnsureDemoMatchingSectionRefusesWhatItCannotExtend(t *testing.T) {
empty := &memoryPolicies{}
if _, err := NewPublisher(empty, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, outbound.ErrPolicyVersionNotFound) {
t.Fatalf("empty family error = %v, want ErrPolicyVersionNotFound", err)
}
calibrated := &memoryPolicies{}
product := domain.DemoProductPolicyV2()
product.Assessment.Calibration = domain.AssessmentCalibrationCalibrated
seedVersion(t, calibrated, domain.PolicyKindCalibrated, product)
if _, err := NewPublisher(calibrated, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, ErrNotDemoPolicy) {
t.Fatalf("calibrated family error = %v, want ErrNotDemoPolicy", err)
}
if len(calibrated.versions) != 1 {
t.Fatalf("versions = %d, want the calibrated family untouched", len(calibrated.versions))
}
}
func TestEnsureDemoMatchingSectionDoesNotRetryAfterAConcurrentPublication(t *testing.T) {
store := &memoryPolicies{}
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2())
store.beforeCreate = func(domain.PolicyVersionDraft) {
store.beforeCreate = nil
// Another operator publishes version 2 first.
if _, err := NewPublisher(store, testClock).Publish(context.Background(), PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "operator:other", Policy: domain.DemoProductPolicyV2(),
}); err != nil {
t.Errorf("concurrent Publish() error = %v", err)
}
}
_, err := NewPublisher(store, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night")
if !errors.Is(err, ErrPolicyChanged) {
t.Fatalf("EnsureDemoMatchingSection() error = %v, want ErrPolicyChanged", err)
}
if len(store.versions) != 2 || store.versions[1].Policy().Matching != nil {
t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions))
}
}