Files
lincodex/backend/internal/domain/policy_document.go
T

655 lines
36 KiB
Go

package domain
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"slices"
)
const (
// productPolicySchemaVersionV1 is the original immutable policy layout.
productPolicySchemaVersionV1 = 1
// productPolicySchemaVersionV2 adds optional policy extensions. Stored
// versions are never rewritten when a newer layout is introduced.
productPolicySchemaVersionV2 = 2
// maxPolicyDocumentBytes bounds a document before decoding. The current
// layout encodes to well under 2 KiB.
maxPolicyDocumentBytes = 64 << 10
)
// PolicyDocumentHash is the SHA-256 of the canonical policy document.
type PolicyDocumentHash [sha256.Size]byte
// The document types mirror ProductPolicy field by field. Required fields are
// pointers, so the decoder can tell a missing field from a zero value: a
// missing field is an error, never a default. Optional attempt, training, and
// support sections are absent only in immutable legacy policy documents.
// Field names carry their unit.
type productPolicyDocument struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
Assessment *assessmentPolicyDocument `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
Support *supportPolicyDocument `json:"support,omitempty"`
Matching *matchingPolicyDocument `json:"matching,omitempty"`
}
// productPolicyV1Document deliberately excludes extension keys. Its strict
// decoder keeps old documents unambiguous even when a newer field is null.
type productPolicyV1Document struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
Assessment *assessmentPolicyV1Document `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
}
type invitationPolicyDocument struct {
ResponseDeadlineOptionsDays *[]CalendarDays `json:"response_deadline_options_days"`
DefaultResponseDeadlineDays *CalendarDays `json:"default_response_deadline_days"`
MaxPendingPerNeed *int32 `json:"max_pending_per_need"`
RepeatAfterDeclineDays *CalendarDays `json:"repeat_after_decline_days"`
InterviewProposalDeadlineBusinessDays *BusinessDays `json:"interview_proposal_deadline_business_days"`
NoDealPauseDays *CalendarDays `json:"no_deal_pause_days"`
}
type organizationQuotaDocument struct {
InvitationWindowDays *CalendarDays `json:"invitation_window_days"`
CardViewWindowHours *Hours `json:"card_view_window_hours"`
Tiers *organizationTiersDocument `json:"tiers"`
}
type organizationTiersDocument struct {
E0 *organizationTierQuotaDocument `json:"e0"`
E1 *organizationTierQuotaDocument `json:"e1"`
E2 *organizationTierQuotaDocument `json:"e2"`
}
type organizationTierQuotaDocument struct {
Active *bool `json:"active"`
InvitationsPerWindow *int32 `json:"invitations_per_window"`
DistinctCardViewsPerWindow *int32 `json:"distinct_card_views_per_window"`
}
type assessmentPolicyDocument struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
PracticeRequired *bool `json:"practice_required"`
StopRule *assessmentStopDocument `json:"stop_rule"`
Attempt *assessmentAttemptDocument `json:"attempt,omitempty"`
Training *assessmentTrainingDocument `json:"training,omitempty"`
Signals *assessmentSignalsDocument `json:"signals,omitempty"`
}
type assessmentPolicyV1Document struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
PracticeRequired *bool `json:"practice_required"`
StopRule *assessmentStopDocument `json:"stop_rule"`
}
type assessmentAttemptDocument struct {
LifetimeHours *Hours `json:"lifetime_hours"`
ChainDeadlineHours *Hours `json:"chain_deadline_hours"`
MaxSessions *int32 `json:"max_sessions"`
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
RealMode *AssessmentRealMode `json:"real_mode"`
BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"`
}
type assessmentSignalsDocument struct {
FastFloorIntegerMS *int32 `json:"fast_floor_integer_ms"`
FastFloorSequenceMS *int32 `json:"fast_floor_sequence_ms"`
FastAnswersAttention *int32 `json:"fast_answers_attention"`
FastAnswersReview *int32 `json:"fast_answers_review"`
DeviationRatioBP *BasisPoints `json:"deviation_ratio_bp"`
DeviationMinAnswers *int32 `json:"deviation_min_answers"`
DeviatingAnswersAttention *int32 `json:"deviating_answers_attention"`
DeviatingAnswersReview *int32 `json:"deviating_answers_review"`
ParallelAlternationsAttention *int32 `json:"parallel_alternations_attention"`
ParallelAlternationsReview *int32 `json:"parallel_alternations_review"`
ExtraNetworksAttention *int32 `json:"extra_networks_attention"`
ExtraNetworksReview *int32 `json:"extra_networks_review"`
DuplicateIntegerCapBits *int32 `json:"duplicate_integer_cap_bits"`
DuplicateSequenceCapBits *int32 `json:"duplicate_sequence_cap_bits"`
DuplicateBitsAttention *int32 `json:"duplicate_bits_attention"`
DuplicateBitsReview *int32 `json:"duplicate_bits_review"`
ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"`
ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"`
ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"`
}
type assessmentTrainingDocument struct {
DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"`
DemoExpressItemCount *int32 `json:"demo_express_item_count"`
MaxSessions *int32 `json:"max_sessions"`
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
}
type assessmentStopDocument struct {
MinScoredItems *int32 `json:"min_scored_items"`
MaxScoredItems *int32 `json:"max_scored_items"`
SeedItems *int32 `json:"seed_items"`
UpperProbabilityBP *BasisPoints `json:"upper_probability_bp"`
LowerProbabilityBP *BasisPoints `json:"lower_probability_bp"`
MaxStandardErrorBP *BasisPoints `json:"max_standard_error_bp"`
}
type identityPolicyDocument struct {
VerificationTokenLifetimeHours *Hours `json:"verification_token_lifetime_hours"`
UnverifiedAccountLifetimeDays *CalendarDays `json:"unverified_account_lifetime_days"`
SessionIdleTimeoutHours *Hours `json:"session_idle_timeout_hours"`
SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"`
}
type matchingPolicyDocument struct {
FitCoverageWeightBP *BasisPoints `json:"fit_coverage_weight_bp"`
FitDomainWeightBP *BasisPoints `json:"fit_domain_weight_bp"`
FitSemanticsWeightBP *BasisPoints `json:"fit_semantics_weight_bp"`
RankFitWeightBP *BasisPoints `json:"rank_fit_weight_bp"`
RankStrengthWeightBP *BasisPoints `json:"rank_strength_weight_bp"`
FreshnessFloorBP *BasisPoints `json:"freshness_floor_bp"`
ResponsivenessFloorBP *BasisPoints `json:"responsiveness_floor_bp"`
CompetitionBoostBP *BasisPoints `json:"competition_boost_bp"`
NeutralUnknownBP *BasisPoints `json:"neutral_unknown_bp"`
NearSkillThresholdBP *BasisPoints `json:"near_skill_threshold_bp"`
RequiredSkillWeight *int32 `json:"required_skill_weight"`
DesiredSkillWeight *int32 `json:"desired_skill_weight"`
TrustStatedBP *BasisPoints `json:"trust_stated_bp"`
TrustOnlineBP *BasisPoints `json:"trust_online_bp"`
TrustIdentityBP *BasisPoints `json:"trust_identity_bp"`
TrustInPersonBP *BasisPoints `json:"trust_in_person_bp"`
AttributionPersonalBP *BasisPoints `json:"attribution_personal_bp"`
AttributionTeamRoleBP *BasisPoints `json:"attribution_team_role_bp"`
AttributionTeamUnattributed *BasisPoints `json:"attribution_team_unattributed_bp"`
RelationExactBP *BasisPoints `json:"relation_exact_bp"`
RelationNarrowerBP *BasisPoints `json:"relation_narrower_bp"`
RelationBroaderBP *BasisPoints `json:"relation_broader_bp"`
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
}
type matchingSkillGroupDocument struct {
Specialization *SpecializationCode `json:"specialization"`
Skills *[]CandidateViewSkillCode `json:"skills"`
}
type searchStatusDocument struct {
SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"`
}
// encodeProductPolicy returns the canonical document: compact JSON with the
// fields in declaration order. The same policy always encodes to the same
// bytes, which makes the document hash deterministic.
func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, error) {
invitations := policy.Invitations
quotas := policy.OrganizationQuotas
assessment := policy.Assessment
identity := policy.Identity
var support *supportPolicyDocument
if policy.Support != nil {
var err error
support, err = encodeSupportPolicy(*policy.Support)
if err != nil {
return nil, PolicyDocumentHash{}, err
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil ||
policy.Support != nil || policy.Matching != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
SchemaVersion: pointer(schemaVersion),
Invitations: &invitationPolicyDocument{
ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions),
DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline),
MaxPendingPerNeed: pointer(invitations.MaxPendingPerNeed),
RepeatAfterDeclineDays: pointer(invitations.RepeatAfterDecline),
InterviewProposalDeadlineBusinessDays: pointer(invitations.InterviewProposalDeadline),
NoDealPauseDays: pointer(invitations.NoDealPause),
},
OrganizationQuotas: &organizationQuotaDocument{
InvitationWindowDays: pointer(quotas.InvitationWindow),
CardViewWindowHours: pointer(quotas.CardViewWindow),
Tiers: &organizationTiersDocument{
E0: encodeTierQuota(quotas.TierE0),
E1: encodeTierQuota(quotas.TierE1),
E2: encodeTierQuota(quotas.TierE2),
},
},
Assessment: &assessmentPolicyDocument{
Calibration: pointer(assessment.Calibration),
SameGradeRetryAfterDays: pointer(assessment.SameGradeRetryAfter),
MaxAttemptsPerWindow: pointer(assessment.MaxAttemptsPerWindow),
AttemptWindowDays: pointer(assessment.AttemptWindow),
PromotionMinIntervalDays: pointer(assessment.PromotionMinInterval),
ConfirmationThresholdBP: pointer(assessment.ConfirmationThreshold),
HighStrengthThresholdBP: pointer(assessment.HighStrengthThreshold),
PracticeRequired: pointer(assessment.PracticeRequired),
StopRule: &assessmentStopDocument{
MinScoredItems: pointer(assessment.StopRule.MinScoredItems),
MaxScoredItems: pointer(assessment.StopRule.MaxScoredItems),
SeedItems: pointer(assessment.StopRule.SeedItems),
UpperProbabilityBP: pointer(assessment.StopRule.UpperProbability),
LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability),
MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError),
},
Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt),
Training: encodeAssessmentTrainingPolicy(assessment.Training),
Signals: encodeAssessmentSignalPolicy(assessment.Signals),
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
UnverifiedAccountLifetimeDays: pointer(identity.UnverifiedAccountLifetime),
SessionIdleTimeoutHours: pointer(identity.SessionIdleTimeout),
SessionAbsoluteLifetimeDays: pointer(identity.SessionAbsoluteLifetime),
},
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
Support: support,
Matching: encodeMatchingPolicy(policy.Matching),
}
encoded, err := json.Marshal(document)
if err != nil {
return nil, PolicyDocumentHash{}, fmt.Errorf("domain.encodeProductPolicy - marshal document: %w", err)
}
return encoded, sha256.Sum256(encoded), nil
}
func encodeAssessmentAttemptPolicy(policy *AssessmentAttemptPolicy) *assessmentAttemptDocument {
if policy == nil {
return nil
}
return &assessmentAttemptDocument{
LifetimeHours: pointer(policy.Lifetime),
ChainDeadlineHours: pointer(policy.ChainDeadline),
MaxSessions: pointer(policy.MaxSessions),
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
RealMode: pointer(policy.RealMode),
BasicPassMarkBP: pointer(policy.BasicPassMark),
}
}
func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmentTrainingDocument {
if policy == nil {
return nil
}
return &assessmentTrainingDocument{
DemoExpressDurationSeconds: pointer(policy.DemoExpressDurationSeconds),
DemoExpressItemCount: pointer(policy.DemoExpressItemCount),
MaxSessions: pointer(policy.MaxSessions),
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
}
}
func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSignalsDocument {
if policy == nil {
return nil
}
return &assessmentSignalsDocument{
FastFloorIntegerMS: pointer(policy.FastFloorIntegerMS),
FastFloorSequenceMS: pointer(policy.FastFloorSequenceMS),
FastAnswersAttention: pointer(policy.FastAnswersAttention),
FastAnswersReview: pointer(policy.FastAnswersReview),
DeviationRatioBP: pointer(policy.DeviationRatio),
DeviationMinAnswers: pointer(policy.DeviationMinAnswers),
DeviatingAnswersAttention: pointer(policy.DeviatingAnswersAttention),
DeviatingAnswersReview: pointer(policy.DeviatingAnswersReview),
ParallelAlternationsAttention: pointer(policy.ParallelAlternationsAttention),
ParallelAlternationsReview: pointer(policy.ParallelAlternationsReview),
ExtraNetworksAttention: pointer(policy.ExtraNetworksAttention),
ExtraNetworksReview: pointer(policy.ExtraNetworksReview),
DuplicateIntegerCapBits: pointer(policy.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: pointer(policy.DuplicateSequenceCapBits),
DuplicateBitsAttention: pointer(policy.DuplicateAttentionBits),
DuplicateBitsReview: pointer(policy.DuplicateReviewBits),
ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention),
}
}
func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
if policy == nil {
return nil
}
return &matchingPolicyDocument{
FitCoverageWeightBP: pointer(policy.FitCoverageWeight),
FitDomainWeightBP: pointer(policy.FitDomainWeight),
FitSemanticsWeightBP: pointer(policy.FitSemanticsWeight),
RankFitWeightBP: pointer(policy.RankFitWeight),
RankStrengthWeightBP: pointer(policy.RankStrengthWeight),
FreshnessFloorBP: pointer(policy.FreshnessFloor),
ResponsivenessFloorBP: pointer(policy.ResponsivenessFloor),
CompetitionBoostBP: pointer(policy.CompetitionBoost),
NeutralUnknownBP: pointer(policy.NeutralUnknown),
NearSkillThresholdBP: pointer(policy.NearSkillThreshold),
RequiredSkillWeight: pointer(policy.RequiredSkillWeight),
DesiredSkillWeight: pointer(policy.DesiredSkillWeight),
TrustStatedBP: pointer(policy.TrustStated),
TrustOnlineBP: pointer(policy.TrustOnline),
TrustIdentityBP: pointer(policy.TrustIdentity),
TrustInPersonBP: pointer(policy.TrustInPerson),
AttributionPersonalBP: pointer(policy.AttributionSelf),
AttributionTeamRoleBP: pointer(policy.AttributionTeamRole),
AttributionTeamUnattributed: pointer(policy.AttributionTeamUnattributed),
RelationExactBP: pointer(policy.RelationExact),
RelationNarrowerBP: pointer(policy.RelationNarrower),
RelationBroaderBP: pointer(policy.RelationBroader),
PercentileMinCohort: pointer(policy.PercentileMinCohort),
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
}
}
func encodeMatchingSkillGroups(groups []MatchingSkillGroup) []matchingSkillGroupDocument {
documents := make([]matchingSkillGroupDocument, 0, len(groups))
for _, group := range groups {
documents = append(documents, matchingSkillGroupDocument{
Specialization: pointer(group.Specialization), Skills: pointer(slices.Clone(group.Skills)),
})
}
return documents
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
InvitationsPerWindow: pointer(quota.InvitationsPerWindow),
DistinctCardViewsPerWindow: pointer(quota.DistinctCardViewsPerWindow),
}
}
// decodeProductPolicy reads a versioned document strictly. It rejects unknown
// fields, missing fields, null required values, values of the wrong type or
// out of the int32 range, unknown schema versions, and trailing data. It
// checks structure only; ProductPolicy.Validate checks the values.
func decodeProductPolicy(document []byte) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
if len(document) > maxPolicyDocumentBytes {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes))
}
version, err := decodeProductPolicySchemaVersion(document)
if err != nil {
return ProductPolicy{}, err
}
var parsed productPolicyDocument
switch version {
case productPolicySchemaVersionV1:
var legacy productPolicyV1Document
if err := decodeStrictPolicyDocument(document, &legacy); err != nil {
return ProductPolicy{}, err
}
parsed = productPolicyDocument{
SchemaVersion: legacy.SchemaVersion,
Invitations: legacy.Invitations,
OrganizationQuotas: legacy.OrganizationQuotas,
Identity: legacy.Identity,
SearchStatus: legacy.SearchStatus,
}
if legacy.Assessment != nil {
assessment := legacy.Assessment
parsed.Assessment = &assessmentPolicyDocument{
Calibration: assessment.Calibration,
SameGradeRetryAfterDays: assessment.SameGradeRetryAfterDays,
MaxAttemptsPerWindow: assessment.MaxAttemptsPerWindow,
AttemptWindowDays: assessment.AttemptWindowDays,
PromotionMinIntervalDays: assessment.PromotionMinIntervalDays,
ConfirmationThresholdBP: assessment.ConfirmationThresholdBP,
HighStrengthThresholdBP: assessment.HighStrengthThresholdBP,
PracticeRequired: assessment.PracticeRequired,
StopRule: assessment.StopRule,
}
}
case productPolicySchemaVersionV2:
if err := decodeStrictPolicyDocument(document, &parsed); err != nil {
return ProductPolicy{}, err
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil)
if !hasAssessmentExtension && parsed.Support == nil && parsed.Matching == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
default:
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d or %d", productPolicySchemaVersionV1, productPolicySchemaVersionV2))
}
return decodeProductPolicyFields(parsed, version)
}
func decodeProductPolicySchemaVersion(document []byte) (int32, error) {
const location = "domain.decodeProductPolicy"
var envelope struct {
SchemaVersion *int32 `json:"schema_version"`
}
decoder := json.NewDecoder(bytes.NewReader(document))
if err := decoder.Decode(&envelope); err != nil {
return 0, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return 0, invalidPolicy(location, "document must contain one JSON object")
}
if envelope.SchemaVersion == nil {
return 0, invalidPolicy(location, "schema_version is required and must be an integer")
}
return *envelope.SchemaVersion, nil
}
func decodeStrictPolicyDocument[T any](document []byte, parsed *T) error {
const location = "domain.decodeProductPolicy"
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
if err := decoder.Decode(parsed); err != nil {
return fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return invalidPolicy(location, "document must contain one JSON object")
}
return nil
}
func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
reader := documentReader{}
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != schemaVersion {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", schemaVersion))
}
invitations := require(&reader, "invitations", parsed.Invitations)
quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas)
tiers := require(&reader, "organization_quotas.tiers", quotas.Tiers)
assessment := require(&reader, "assessment", parsed.Assessment)
stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule)
identity := require(&reader, "identity", parsed.Identity)
searchStatus := require(&reader, "search_status", parsed.SearchStatus)
var attemptPolicy *AssessmentAttemptPolicy
if assessment.Attempt != nil {
attempt := assessment.Attempt
attemptPolicy = &AssessmentAttemptPolicy{
Lifetime: require(&reader, "assessment.attempt.lifetime_hours", attempt.LifetimeHours),
ChainDeadline: require(&reader, "assessment.attempt.chain_deadline_hours", attempt.ChainDeadlineHours),
MaxSessions: require(&reader, "assessment.attempt.max_sessions", attempt.MaxSessions),
IdleTimeoutSeconds: require(&reader, "assessment.attempt.idle_timeout_seconds", attempt.IdleTimeoutSeconds),
RealMode: require(&reader, "assessment.attempt.real_mode", attempt.RealMode),
BasicPassMark: require(&reader, "assessment.attempt.basic_pass_mark_bp", attempt.BasicPassMarkBP),
}
}
var trainingPolicy *AssessmentTrainingPolicy
if assessment.Training != nil {
training := assessment.Training
trainingPolicy = &AssessmentTrainingPolicy{
DemoExpressDurationSeconds: require(&reader, "assessment.training.demo_express_duration_seconds", training.DemoExpressDurationSeconds),
DemoExpressItemCount: require(&reader, "assessment.training.demo_express_item_count", training.DemoExpressItemCount),
MaxSessions: require(&reader, "assessment.training.max_sessions", training.MaxSessions),
IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds),
}
}
var signalPolicy *AssessmentSignalPolicy
if assessment.Signals != nil {
signals := assessment.Signals
signalPolicy = &AssessmentSignalPolicy{
FastFloorIntegerMS: require(&reader, "assessment.signals.fast_floor_integer_ms", signals.FastFloorIntegerMS),
FastFloorSequenceMS: require(&reader, "assessment.signals.fast_floor_sequence_ms", signals.FastFloorSequenceMS),
FastAnswersAttention: require(&reader, "assessment.signals.fast_answers_attention", signals.FastAnswersAttention),
FastAnswersReview: require(&reader, "assessment.signals.fast_answers_review", signals.FastAnswersReview),
DeviationRatio: require(&reader, "assessment.signals.deviation_ratio_bp", signals.DeviationRatioBP),
DeviationMinAnswers: require(&reader, "assessment.signals.deviation_min_answers", signals.DeviationMinAnswers),
DeviatingAnswersAttention: require(&reader, "assessment.signals.deviating_answers_attention", signals.DeviatingAnswersAttention),
DeviatingAnswersReview: require(&reader, "assessment.signals.deviating_answers_review", signals.DeviatingAnswersReview),
ParallelAlternationsAttention: require(&reader, "assessment.signals.parallel_alternations_attention", signals.ParallelAlternationsAttention),
ParallelAlternationsReview: require(&reader, "assessment.signals.parallel_alternations_review", signals.ParallelAlternationsReview),
ExtraNetworksAttention: require(&reader, "assessment.signals.extra_networks_attention", signals.ExtraNetworksAttention),
ExtraNetworksReview: require(&reader, "assessment.signals.extra_networks_review", signals.ExtraNetworksReview),
DuplicateIntegerCapBits: require(&reader, "assessment.signals.duplicate_integer_cap_bits", signals.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: require(&reader, "assessment.signals.duplicate_sequence_cap_bits", signals.DuplicateSequenceCapBits),
DuplicateAttentionBits: require(&reader, "assessment.signals.duplicate_bits_attention", signals.DuplicateBitsAttention),
DuplicateReviewBits: require(&reader, "assessment.signals.duplicate_bits_review", signals.DuplicateBitsReview),
ClientFocusLossAttentionMS: require(&reader, "assessment.signals.client_focus_loss_attention_ms", signals.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: require(&reader, "assessment.signals.client_clipboard_events_attention", signals.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: require(&reader, "assessment.signals.client_fullscreen_exits_attention", signals.ClientFullscreenExitsAttention),
}
}
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
DefaultResponseDeadline: require(&reader, "invitations.default_response_deadline_days", invitations.DefaultResponseDeadlineDays),
MaxPendingPerNeed: require(&reader, "invitations.max_pending_per_need", invitations.MaxPendingPerNeed),
RepeatAfterDecline: require(&reader, "invitations.repeat_after_decline_days", invitations.RepeatAfterDeclineDays),
InterviewProposalDeadline: require(&reader, "invitations.interview_proposal_deadline_business_days", invitations.InterviewProposalDeadlineBusinessDays),
NoDealPause: require(&reader, "invitations.no_deal_pause_days", invitations.NoDealPauseDays),
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: require(&reader, "organization_quotas.invitation_window_days", quotas.InvitationWindowDays),
CardViewWindow: require(&reader, "organization_quotas.card_view_window_hours", quotas.CardViewWindowHours),
TierE0: decodeTierQuota(&reader, "organization_quotas.tiers.e0", tiers.E0),
TierE1: decodeTierQuota(&reader, "organization_quotas.tiers.e1", tiers.E1),
TierE2: decodeTierQuota(&reader, "organization_quotas.tiers.e2", tiers.E2),
},
Assessment: AssessmentPolicy{
Calibration: require(&reader, "assessment.calibration", assessment.Calibration),
SameGradeRetryAfter: require(&reader, "assessment.same_grade_retry_after_days", assessment.SameGradeRetryAfterDays),
MaxAttemptsPerWindow: require(&reader, "assessment.max_attempts_per_window", assessment.MaxAttemptsPerWindow),
AttemptWindow: require(&reader, "assessment.attempt_window_days", assessment.AttemptWindowDays),
PromotionMinInterval: require(&reader, "assessment.promotion_min_interval_days", assessment.PromotionMinIntervalDays),
ConfirmationThreshold: require(&reader, "assessment.confirmation_threshold_bp", assessment.ConfirmationThresholdBP),
HighStrengthThreshold: require(&reader, "assessment.high_strength_threshold_bp", assessment.HighStrengthThresholdBP),
PracticeRequired: require(&reader, "assessment.practice_required", assessment.PracticeRequired),
StopRule: AssessmentStopRule{
MinScoredItems: require(&reader, "assessment.stop_rule.min_scored_items", stopRule.MinScoredItems),
MaxScoredItems: require(&reader, "assessment.stop_rule.max_scored_items", stopRule.MaxScoredItems),
SeedItems: require(&reader, "assessment.stop_rule.seed_items", stopRule.SeedItems),
UpperProbability: require(&reader, "assessment.stop_rule.upper_probability_bp", stopRule.UpperProbabilityBP),
LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP),
MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP),
},
Attempt: attemptPolicy,
Training: trainingPolicy,
Signals: signalPolicy,
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
UnverifiedAccountLifetime: require(&reader, "identity.unverified_account_lifetime_days", identity.UnverifiedAccountLifetimeDays),
SessionIdleTimeout: require(&reader, "identity.session_idle_timeout_hours", identity.SessionIdleTimeoutHours),
SessionAbsoluteLifetime: require(&reader, "identity.session_absolute_lifetime_days", identity.SessionAbsoluteLifetimeDays),
},
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
Matching: decodeOptionalMatchingPolicy(&reader, parsed.Matching),
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
}
return policy, nil
}
// decodeOptionalMatchingPolicy keeps documents that predate the matching
// section without it and never fills an omitted section with demo values.
func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPolicyDocument) *MatchingPolicy {
if document == nil {
return nil
}
taxonomy := make([]MatchingSkillGroup, 0)
for _, group := range require(reader, "matching.skill_taxonomy", document.SkillTaxonomy) {
taxonomy = append(taxonomy, MatchingSkillGroup{
Specialization: require(reader, "matching.skill_taxonomy.specialization", group.Specialization),
Skills: require(reader, "matching.skill_taxonomy.skills", group.Skills),
})
}
return &MatchingPolicy{
FitCoverageWeight: require(reader, "matching.fit_coverage_weight_bp", document.FitCoverageWeightBP),
FitDomainWeight: require(reader, "matching.fit_domain_weight_bp", document.FitDomainWeightBP),
FitSemanticsWeight: require(reader, "matching.fit_semantics_weight_bp", document.FitSemanticsWeightBP),
RankFitWeight: require(reader, "matching.rank_fit_weight_bp", document.RankFitWeightBP),
RankStrengthWeight: require(reader, "matching.rank_strength_weight_bp", document.RankStrengthWeightBP),
FreshnessFloor: require(reader, "matching.freshness_floor_bp", document.FreshnessFloorBP),
ResponsivenessFloor: require(reader, "matching.responsiveness_floor_bp", document.ResponsivenessFloorBP),
CompetitionBoost: require(reader, "matching.competition_boost_bp", document.CompetitionBoostBP),
NeutralUnknown: require(reader, "matching.neutral_unknown_bp", document.NeutralUnknownBP),
NearSkillThreshold: require(reader, "matching.near_skill_threshold_bp", document.NearSkillThresholdBP),
RequiredSkillWeight: require(reader, "matching.required_skill_weight", document.RequiredSkillWeight),
DesiredSkillWeight: require(reader, "matching.desired_skill_weight", document.DesiredSkillWeight),
TrustStated: require(reader, "matching.trust_stated_bp", document.TrustStatedBP),
TrustOnline: require(reader, "matching.trust_online_bp", document.TrustOnlineBP),
TrustIdentity: require(reader, "matching.trust_identity_bp", document.TrustIdentityBP),
TrustInPerson: require(reader, "matching.trust_in_person_bp", document.TrustInPersonBP),
AttributionSelf: require(reader, "matching.attribution_personal_bp", document.AttributionPersonalBP),
AttributionTeamRole: require(reader, "matching.attribution_team_role_bp", document.AttributionTeamRoleBP),
AttributionTeamUnattributed: require(reader, "matching.attribution_team_unattributed_bp", document.AttributionTeamUnattributed),
RelationExact: require(reader, "matching.relation_exact_bp", document.RelationExactBP),
RelationNarrower: require(reader, "matching.relation_narrower_bp", document.RelationNarrowerBP),
RelationBroader: require(reader, "matching.relation_broader_bp", document.RelationBroaderBP),
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
SkillTaxonomy: taxonomy,
}
}
func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota {
tier := require(reader, field, document)
return OrganizationTierQuota{
Active: require(reader, field+".active", tier.Active),
InvitationsPerWindow: require(reader, field+".invitations_per_window", tier.InvitationsPerWindow),
DistinctCardViewsPerWindow: require(reader, field+".distinct_card_views_per_window", tier.DistinctCardViewsPerWindow),
}
}
// documentReader remembers the first missing field while a document is read.
type documentReader struct {
missing string
}
// require returns the value behind a document pointer, or the zero value
// after recording field as missing.
func require[T any](reader *documentReader, field string, value *T) T {
if value == nil {
if reader.missing == "" {
reader.missing = field
}
var zero T
return zero
}
return *value
}
func pointer[T any](value T) *T { return &value }