Files

267 lines
11 KiB
Go

package domain
import (
"fmt"
"math"
"slices"
"time"
)
const (
MaxNeedCreationResultBytes = 524288
MaxNeedCreationResultStorageBytes = MaxNeedCreationResultBytes + MaxNeedJSONBTextHeadroom
)
// NeedRecommendationStatus is the public state of category calculation.
type NeedRecommendationStatus string
const (
NeedRecommendationsComputed NeedRecommendationStatus = "computed"
NeedRecommendationsPending NeedRecommendationStatus = "pending"
NeedRecommendationsNotAvailable NeedRecommendationStatus = "not_available"
)
type NeedMoneyStatus string
const (
NeedMoneyComputed NeedMoneyStatus = "computed"
NeedMoneyInsufficientData NeedMoneyStatus = "insufficient_data"
NeedMoneyNoSalary NeedMoneyStatus = "no_salary"
NeedMoneyWithheld NeedMoneyStatus = "withheld"
)
type NeedSupplyBand string
const (
NeedSupplyFewerThanFive NeedSupplyBand = "fewer_than_5"
NeedSupplyFromFiveTo29 NeedSupplyBand = "from_5_to_29"
NeedSupply30OrMore NeedSupplyBand = "30_or_more"
)
// NeedSkillOverlap is the public category skill coverage component.
type NeedSkillOverlap struct {
Share float64 `json:"share"`
CoveredSkills []string `json:"covered_skills"`
UncoveredSkills []string `json:"uncovered_skills"`
}
// NeedMoneyFit is the privacy-preserving public salary component.
type NeedMoneyFit struct {
Status NeedMoneyStatus `json:"status"`
Share *float64 `json:"share"`
}
// NeedCategoryRecommendation is one category and the public components used
// to rank it. It contains no candidate-level salary information.
type NeedCategoryRecommendation struct {
Specialization SpecializationCode `json:"specialization"`
Grade GradeCode `json:"grade"`
Score *float64 `json:"score"`
SkillOverlap NeedSkillOverlap `json:"skill_overlap"`
Money NeedMoneyFit `json:"money"`
Supply NeedSupplyBand `json:"supply"`
}
// NeedCategoryRecommendations is the server's versioned public calculation
// state for the confirmed requirements.
type NeedCategoryRecommendations struct {
Status NeedRecommendationStatus `json:"status"`
RequirementsVersion int64 `json:"requirements_version"`
PolicyVersion *int32 `json:"policy_version"`
AlgorithmVersion *string `json:"algorithm_version"`
ComputedAt *time.Time `json:"computed_at"`
Categories []NeedCategoryRecommendation `json:"categories"`
}
// NeedResponseSnapshot is an immutable public result captured when an
// idempotent create succeeds. Replay uses this snapshot instead of reading a
// later need version or recomputing readiness or recommendations.
type NeedResponseSnapshot struct {
Need NeedSnapshot `json:"need"`
Readiness NeedReadinessReport `json:"readiness"`
Recommendations NeedCategoryRecommendations `json:"recommendations"`
}
// NeedResponseSnapshot returns the current public result without exposing
// private rejected suggestion state to the response mapper.
func (need Need) ResponseSnapshot() NeedResponseSnapshot {
return NeedResponseSnapshot{
Need: need.Snapshot(), Readiness: need.Readiness(), Recommendations: need.Recommendations(),
}
}
// Recommendations returns the honest current MVP state. It never fabricates
// a computed category result while the calculator is unavailable.
func (need Need) Recommendations() NeedCategoryRecommendations {
status := NeedRecommendationsNotAvailable
if hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills) {
status = NeedRecommendationsPending
}
return NeedCategoryRecommendations{
Status: status, RequirementsVersion: need.RequirementsVersion(),
Categories: []NeedCategoryRecommendation{},
}
}
// RestoreNeedResponseSnapshot validates and defensively copies an immutable
// create result read from storage.
func RestoreNeedResponseSnapshot(snapshot NeedResponseSnapshot) (NeedResponseSnapshot, error) {
const location = "domain.RestoreNeedResponseSnapshot"
need, err := RestoreNeed(snapshot.Need)
if err != nil {
return NeedResponseSnapshot{}, fmt.Errorf("%s - restore need: %w", location, err)
}
if err := validateNeedReadiness(location, snapshot.Readiness); err != nil {
return NeedResponseSnapshot{}, err
}
if err := validateNeedRecommendations(location, need, snapshot.Recommendations); err != nil {
return NeedResponseSnapshot{}, err
}
snapshot.Need = need.Snapshot()
snapshot.Readiness = cloneNeedReadiness(snapshot.Readiness)
snapshot.Recommendations = cloneNeedRecommendations(snapshot.Recommendations)
return snapshot, nil
}
func validateNeedReadiness(location string, readiness NeedReadinessReport) error {
if readiness.MissingFields == nil || len(readiness.MissingFields) > 9 {
return invalidNeed(location, "stored readiness fields are outside their bound")
}
if readiness.Status != NeedReadinessComplete && readiness.Status != NeedReadinessIncomplete {
return invalidNeed(location, "stored readiness status is unknown")
}
seen := make(map[NeedMissingFieldName]struct{}, len(readiness.MissingFields))
for _, missing := range readiness.MissingFields {
if !knownNeedMissingField(missing.Field) || (missing.Reason != NeedMissingUnknown && missing.Reason != NeedMissingUnconfirmed) || !validNeedText(missing.Question, 300) {
return invalidNeed(location, "stored readiness field is invalid")
}
if _, exists := seen[missing.Field]; exists {
return invalidNeed(location, "stored readiness field is duplicated")
}
seen[missing.Field] = struct{}{}
}
if (readiness.Status == NeedReadinessComplete) != (len(readiness.MissingFields) == 0) {
return invalidNeed(location, "stored readiness status does not match its fields")
}
return nil
}
func knownNeedMissingField(field NeedMissingFieldName) bool {
switch field {
case NeedMissingSpecialization, NeedMissingGrade, NeedMissingRequiredSkills, NeedMissingWorkFormats, NeedMissingLocation, NeedMissingSalary:
return true
default:
return false
}
}
func validateNeedRecommendations(location string, need Need, recommendations NeedCategoryRecommendations) error {
if recommendations.RequirementsVersion != need.RequirementsVersion() || recommendations.Categories == nil || len(recommendations.Categories) > 10 {
return invalidNeed(location, "stored recommendation snapshot is outside its bound")
}
hasConfirmedSkill := hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills)
switch recommendations.Status {
case NeedRecommendationsPending, NeedRecommendationsNotAvailable:
return validateUncalculatedRecommendations(location, recommendations, hasConfirmedSkill)
case NeedRecommendationsComputed:
return validateComputedRecommendations(location, recommendations, hasConfirmedSkill)
default:
return invalidNeed(location, "stored recommendation status is unknown")
}
}
func validateUncalculatedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
shouldBePending := recommendations.Status == NeedRecommendationsPending
if recommendations.PolicyVersion != nil || recommendations.AlgorithmVersion != nil || recommendations.ComputedAt != nil || len(recommendations.Categories) != 0 ||
shouldBePending != hasConfirmedSkill {
return invalidNeed(location, "uncalculated recommendations must not contain calculation data")
}
return nil
}
func validateComputedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
if !hasConfirmedSkill || recommendations.PolicyVersion == nil || *recommendations.PolicyVersion < 1 || recommendations.AlgorithmVersion == nil ||
!validNeedVersionLabel(*recommendations.AlgorithmVersion) || recommendations.ComputedAt == nil || !validNeedTimestamp(*recommendations.ComputedAt) {
return invalidNeed(location, "computed recommendations require a valid policy, algorithm, and timestamp")
}
return validateNeedRecommendationCategories(location, recommendations.Categories)
}
func validateNeedRecommendationCategories(location string, categories []NeedCategoryRecommendation) error {
seen := make(map[string]struct{}, len(categories))
for _, category := range categories {
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() || !validOptionalNeedScore(category.Score) || !validOptionalNeedScore(&category.SkillOverlap.Share) ||
category.SkillOverlap.CoveredSkills == nil || category.SkillOverlap.UncoveredSkills == nil || len(category.SkillOverlap.CoveredSkills) > 60 || len(category.SkillOverlap.UncoveredSkills) > 60 ||
!validNeedMoneyFit(category.Money) || !validNeedSupplyBand(category.Supply) {
return invalidNeed(location, "stored recommendation category is invalid")
}
key := string(category.Specialization) + "\x00" + string(category.Grade)
if _, exists := seen[key]; exists {
return invalidNeed(location, "stored recommendation category is duplicated")
}
seen[key] = struct{}{}
for _, skill := range append(slices.Clone(category.SkillOverlap.CoveredSkills), category.SkillOverlap.UncoveredSkills...) {
if !validNeedText(skill, maxNeedNameRunes) {
return invalidNeed(location, "stored recommendation skill is invalid")
}
}
}
return nil
}
func validOptionalNeedScore(value *float64) bool {
return value == nil || !math.IsNaN(*value) && !math.IsInf(*value, 0) && *value >= 0 && *value <= 1
}
func validNeedMoneyFit(value NeedMoneyFit) bool {
switch value.Status {
case NeedMoneyComputed:
if value.Share == nil || !validOptionalNeedScore(value.Share) {
return false
}
case NeedMoneyInsufficientData, NeedMoneyNoSalary, NeedMoneyWithheld:
if value.Share != nil {
return false
}
default:
return false
}
return true
}
func validNeedSupplyBand(value NeedSupplyBand) bool {
return value == NeedSupplyFewerThanFive || value == NeedSupplyFromFiveTo29 || value == NeedSupply30OrMore
}
func cloneNeedReadiness(readiness NeedReadinessReport) NeedReadinessReport {
readiness.MissingFields = slices.Clone(readiness.MissingFields)
return readiness
}
func cloneNeedRecommendations(recommendations NeedCategoryRecommendations) NeedCategoryRecommendations {
cloned := recommendations
if recommendations.PolicyVersion != nil {
value := *recommendations.PolicyVersion
cloned.PolicyVersion = &value
}
if recommendations.AlgorithmVersion != nil {
value := *recommendations.AlgorithmVersion
cloned.AlgorithmVersion = &value
}
if recommendations.ComputedAt != nil {
value := canonicalNeedTime(*recommendations.ComputedAt)
cloned.ComputedAt = &value
}
cloned.Categories = slices.Clone(recommendations.Categories)
for index := range cloned.Categories {
cloned.Categories[index].Score = cloneNeedPointer(recommendations.Categories[index].Score)
cloned.Categories[index].SkillOverlap.CoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.CoveredSkills)
cloned.Categories[index].SkillOverlap.UncoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.UncoveredSkills)
cloned.Categories[index].Money.Share = cloneNeedPointer(recommendations.Categories[index].Money.Share)
}
return cloned
}
func (snapshot NeedResponseSnapshot) String() string { return redactedNeed }
func (snapshot NeedResponseSnapshot) GoString() string { return redactedNeed }