518 lines
18 KiB
Go
518 lines
18 KiB
Go
package assessment
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
var ErrAssessmentAvailabilityNotImplemented = errors.New("assessment availability is not implemented for the effective policy")
|
|
|
|
type AvailabilityStatus string
|
|
|
|
const (
|
|
AvailabilityStatusAvailable AvailabilityStatus = "available"
|
|
AvailabilityStatusActiveAttempt AvailabilityStatus = "active_attempt"
|
|
AvailabilityStatusCooldown AvailabilityStatus = "cooldown"
|
|
AvailabilityStatusInsufficientBank AvailabilityStatus = "insufficient_bank"
|
|
)
|
|
|
|
type AssessmentAvailability struct {
|
|
Specializations []SpecializationAvailability
|
|
}
|
|
|
|
type SpecializationAvailability struct {
|
|
Specialization domain.SpecializationCode
|
|
ConfirmedGrade *domain.GradeCode
|
|
ActiveAttemptID *domain.AssessmentAttemptID
|
|
Grades []GradeAvailability
|
|
}
|
|
|
|
type GradeAvailability struct {
|
|
Grade domain.GradeCode
|
|
Status AvailabilityStatus
|
|
Mode *domain.AssessmentRealMode
|
|
AvailableAt *time.Time
|
|
TimeLimitSeconds *int32
|
|
MaxSessions *int32
|
|
MaxItems *int32
|
|
PracticeRequired *bool
|
|
}
|
|
|
|
// GetMyAssessmentAvailability is a read-only candidate preflight. All
|
|
// repositories run under one repeatable-read snapshot so policy, bank,
|
|
// questionnaire, attempts, and disclosed families agree on one database view.
|
|
func (service *AttemptService) GetMyAssessmentAvailability(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
) (AssessmentAvailability, error) {
|
|
const location = "AttemptService.GetMyAssessmentAvailability"
|
|
var availability AssessmentAvailability
|
|
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
|
|
return err
|
|
}
|
|
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read snapshot database time: %w", location, err)
|
|
}
|
|
now = now.UTC().Truncate(time.Microsecond)
|
|
assessmentPolicy, err := readAvailabilityPolicy(ctx, unit, now)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read effective assessment policy: %w", location, err)
|
|
}
|
|
questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read candidate questionnaire: %w", location, err)
|
|
}
|
|
availability, err = buildAssessmentAvailability(ctx, unit, userID, now, assessmentPolicy, questionnaire)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build assessment availability: %w", location, err)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return AssessmentAvailability{}, fmt.Errorf("%s - read snapshot: %w", location, err)
|
|
}
|
|
return availability, nil
|
|
}
|
|
|
|
func readAvailabilityPolicy(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
now time.Time,
|
|
) (domain.AssessmentPolicy, error) {
|
|
const location = "assessment.readAvailabilityPolicy"
|
|
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
|
|
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
|
return domain.AssessmentPolicy{}, fmt.Errorf("%s - no effective assessment policy: %w", location, ErrAssessmentAvailabilityNotImplemented)
|
|
}
|
|
if err != nil {
|
|
return domain.AssessmentPolicy{}, err
|
|
}
|
|
policy := version.Policy().Assessment
|
|
if policy.Attempt == nil || policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic {
|
|
return domain.AssessmentPolicy{}, fmt.Errorf("%s - effective real assessment mode is not implemented: %w", location, ErrAssessmentAvailabilityNotImplemented)
|
|
}
|
|
return policy, nil
|
|
}
|
|
|
|
type assessmentAvailabilityReads struct {
|
|
selections []outbound.AssessmentAvailabilitySelection
|
|
active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary
|
|
rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary
|
|
quota outbound.AssessmentRootQuotaSnapshot
|
|
seen map[domain.AssessmentFamilyKey]struct{}
|
|
}
|
|
|
|
func buildAssessmentAvailability(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
userID uuid.UUID,
|
|
now time.Time,
|
|
policy domain.AssessmentPolicy,
|
|
questionnaire domain.CandidateQuestionnaire,
|
|
) (AssessmentAvailability, error) {
|
|
reads, err := readAssessmentAvailability(ctx, unit, userID, now, policy, questionnaire)
|
|
if err != nil {
|
|
return AssessmentAvailability{}, err
|
|
}
|
|
seconds, err := assessmentLimitSeconds(policy.Attempt.Lifetime.Duration())
|
|
if err != nil {
|
|
return AssessmentAvailability{}, err
|
|
}
|
|
itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems
|
|
result := AssessmentAvailability{Specializations: make([]SpecializationAvailability, 0, len(questionnaire.Specializations()))}
|
|
for _, answer := range questionnaire.Specializations() {
|
|
result.Specializations = append(result.Specializations, buildSpecializationAvailability(
|
|
answer, reads, policy, now, seconds, itemCount,
|
|
))
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func assessmentLimitSeconds(duration time.Duration) (int32, error) {
|
|
seconds := duration / time.Second
|
|
if seconds <= 0 || seconds > time.Duration(1<<31-1) {
|
|
return 0, fmt.Errorf("assessment availability limit exceeds supported seconds: %w", domain.ErrInvalidPolicy)
|
|
}
|
|
return int32(seconds), nil
|
|
}
|
|
|
|
func readAssessmentAvailability(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
userID uuid.UUID,
|
|
now time.Time,
|
|
policy domain.AssessmentPolicy,
|
|
questionnaire domain.CandidateQuestionnaire,
|
|
) (assessmentAvailabilityReads, error) {
|
|
const location = "assessment.readAssessmentAvailability"
|
|
selections, err := unit.AssessmentBank().ListCurrentAssessmentAvailabilitySelections(ctx, now)
|
|
if err != nil {
|
|
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read bank: %w", location, err)
|
|
}
|
|
reads := assessmentAvailabilityReads{selections: selections}
|
|
reads.active, err = readActiveAvailabilityAttempts(ctx, unit, userID, now, questionnaire)
|
|
if err != nil {
|
|
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err)
|
|
}
|
|
window := policy.AttemptWindow.Duration()
|
|
reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot(
|
|
ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow,
|
|
)
|
|
if err != nil {
|
|
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root quota: %w", location, err)
|
|
}
|
|
reads.rootHistory, err = readAvailabilityRootHistory(ctx, unit, userID, now, policy, questionnaire)
|
|
if err != nil {
|
|
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root retry history: %w", location, err)
|
|
}
|
|
keys, err := unit.AssessmentAttempts().ListDisclosedFamilyKeys(ctx, userID, now.Add(-365*24*time.Hour))
|
|
if err != nil {
|
|
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read disclosed families: %w", location, err)
|
|
}
|
|
reads.seen = make(map[domain.AssessmentFamilyKey]struct{}, len(keys))
|
|
for _, key := range keys {
|
|
reads.seen[key] = struct{}{}
|
|
}
|
|
return reads, nil
|
|
}
|
|
|
|
func readActiveAvailabilityAttempts(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
userID uuid.UUID,
|
|
now time.Time,
|
|
questionnaire domain.CandidateQuestionnaire,
|
|
) (map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary, error) {
|
|
activeBySpecialization := make(map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary)
|
|
for _, answer := range questionnaire.Specializations() {
|
|
active, found, err := unit.AssessmentAttempts().GetAvailabilityActiveAttempt(ctx, userID, answer.Specialization)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if found && active.ExpiresAt.After(now) {
|
|
activeBySpecialization[answer.Specialization] = active
|
|
}
|
|
}
|
|
return activeBySpecialization, nil
|
|
}
|
|
|
|
func readAvailabilityRootHistory(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
userID uuid.UUID,
|
|
now time.Time,
|
|
policy domain.AssessmentPolicy,
|
|
questionnaire domain.CandidateQuestionnaire,
|
|
) (map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary, error) {
|
|
horizon := max(policy.AttemptWindow.Duration(), policy.SameGradeRetryAfter.Duration(),
|
|
policy.PromotionMinInterval.Duration()) + policy.Attempt.ChainDeadline.Duration()
|
|
history := make(map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary)
|
|
for _, answer := range questionnaire.Specializations() {
|
|
rows, err := unit.AssessmentAttempts().ListAvailabilityRootSummaries(
|
|
ctx, userID, answer.Specialization, now.Add(-horizon),
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
history[answer.Specialization] = rows
|
|
}
|
|
return history, nil
|
|
}
|
|
|
|
func buildSpecializationAvailability(
|
|
answer domain.QuestionnaireSpecialization,
|
|
reads assessmentAvailabilityReads,
|
|
policy domain.AssessmentPolicy,
|
|
now time.Time,
|
|
seconds, itemCount int32,
|
|
) SpecializationAvailability {
|
|
active, hasActive := reads.active[answer.Specialization]
|
|
result := SpecializationAvailability{
|
|
Specialization: answer.Specialization,
|
|
Grades: make([]GradeAvailability, 0, len(availabilityGrades)),
|
|
}
|
|
if hasActive {
|
|
id := active.ID
|
|
result.ActiveAttemptID = &id
|
|
}
|
|
for _, grade := range availabilityGrades {
|
|
result.Grades = append(result.Grades, buildGradeAvailability(
|
|
answer, grade, reads, policy, now, seconds, itemCount, hasActive,
|
|
))
|
|
}
|
|
return result
|
|
}
|
|
|
|
func buildGradeAvailability(
|
|
answer domain.QuestionnaireSpecialization,
|
|
grade domain.GradeCode,
|
|
reads assessmentAvailabilityReads,
|
|
policy domain.AssessmentPolicy,
|
|
now time.Time,
|
|
seconds, itemCount int32,
|
|
hasActive bool,
|
|
) GradeAvailability {
|
|
result := GradeAvailability{Grade: grade}
|
|
if hasActive {
|
|
result.Status = AvailabilityStatusActiveAttempt
|
|
} else if !hasSufficientUnseenBank(answer, grade, reads.selections, reads.seen, itemCount) {
|
|
result.Status = AvailabilityStatusInsufficientBank
|
|
return result
|
|
} else if availableAt := rootCooldownUntil(reads.rootHistory[answer.Specialization], grade, policy, reads.quota, now); availableAt != nil {
|
|
result.Status = AvailabilityStatusCooldown
|
|
result.AvailableAt = availableAt
|
|
} else {
|
|
result.Status = AvailabilityStatusAvailable
|
|
}
|
|
mode := policy.Attempt.RealMode
|
|
result.setLimits(mode, seconds, policy.Attempt.MaxSessions, itemCount, false)
|
|
return result
|
|
}
|
|
|
|
var availabilityGrades = [...]domain.GradeCode{
|
|
domain.GradeIntern, domain.GradeJunior, domain.GradeMiddle, domain.GradeSenior,
|
|
}
|
|
|
|
func (grade *GradeAvailability) setLimits(
|
|
mode domain.AssessmentRealMode,
|
|
seconds, maxSessions, maxItems int32,
|
|
practiceRequired bool,
|
|
) {
|
|
grade.Mode = &mode
|
|
grade.TimeLimitSeconds = &seconds
|
|
grade.MaxSessions = &maxSessions
|
|
grade.MaxItems = &maxItems
|
|
grade.PracticeRequired = &practiceRequired
|
|
}
|
|
|
|
func hasSufficientUnseenBank(
|
|
answer domain.QuestionnaireSpecialization,
|
|
grade domain.GradeCode,
|
|
selections []outbound.AssessmentAvailabilitySelection,
|
|
seen map[domain.AssessmentFamilyKey]struct{},
|
|
minimum int32,
|
|
) bool {
|
|
catalogLanguages := availabilityLanguages(answer.Specialization, selections)
|
|
if len(catalogLanguages) > 0 && len(answer.TaskLanguages) == 0 {
|
|
return false
|
|
}
|
|
languages := answer.TaskLanguages
|
|
if len(catalogLanguages) == 0 {
|
|
if len(languages) > 0 {
|
|
return false
|
|
}
|
|
languages = []domain.TaskLanguageCode{""}
|
|
}
|
|
for _, language := range languages {
|
|
if len(catalogLanguages) > 0 && !slices.Contains(catalogLanguages, language) {
|
|
continue
|
|
}
|
|
selection, found := uniqueAvailabilitySelection(selections, answer.Specialization, grade, language)
|
|
if !found {
|
|
continue
|
|
}
|
|
unseen := int32(0)
|
|
for _, key := range selection.FamilyKeys {
|
|
if _, exists := seen[key]; !exists {
|
|
unseen++
|
|
}
|
|
}
|
|
if unseen >= minimum {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func availabilityLanguages(
|
|
specialization domain.SpecializationCode,
|
|
selections []outbound.AssessmentAvailabilitySelection,
|
|
) []domain.TaskLanguageCode {
|
|
var languages []domain.TaskLanguageCode
|
|
for _, selection := range selections {
|
|
if selection.Specialization != specialization {
|
|
continue
|
|
}
|
|
for _, language := range selection.TaskLanguages {
|
|
if !slices.Contains(languages, language) {
|
|
languages = append(languages, language)
|
|
}
|
|
}
|
|
}
|
|
return languages
|
|
}
|
|
|
|
func uniqueAvailabilitySelection(
|
|
selections []outbound.AssessmentAvailabilitySelection,
|
|
specialization domain.SpecializationCode,
|
|
grade domain.GradeCode,
|
|
language domain.TaskLanguageCode,
|
|
) (outbound.AssessmentAvailabilitySelection, bool) {
|
|
var match outbound.AssessmentAvailabilitySelection
|
|
count := 0
|
|
for _, selection := range selections {
|
|
if selection.Specialization != specialization || selection.Grade != grade {
|
|
continue
|
|
}
|
|
if language == "" && len(selection.TaskLanguages) == 0 || slices.Contains(selection.TaskLanguages, language) {
|
|
match = selection
|
|
count++
|
|
}
|
|
}
|
|
return match, count == 1
|
|
}
|
|
|
|
func rootCooldownUntil(
|
|
roots []outbound.AssessmentRootAvailabilitySummary,
|
|
target domain.GradeCode,
|
|
policy domain.AssessmentPolicy,
|
|
quota outbound.AssessmentRootQuotaSnapshot,
|
|
now time.Time,
|
|
) *time.Time {
|
|
latest, latestSameGrade := latestAvailabilityRoots(roots, target)
|
|
var blockedUntil time.Time
|
|
blockedUntil = sameGradeAvailabilityCooldown(blockedUntil, latestSameGrade, policy, now)
|
|
blockedUntil = latestRootAvailabilityCooldown(blockedUntil, latest, target, policy, now)
|
|
if quota.Count >= policy.MaxAttemptsPerWindow && quota.AvailableAt != nil {
|
|
blockedUntil = laterAvailability(blockedUntil, *quota.AvailableAt, now)
|
|
}
|
|
if blockedUntil.IsZero() {
|
|
return nil
|
|
}
|
|
availableAt := blockedUntil.UTC().Truncate(time.Microsecond)
|
|
return &availableAt
|
|
}
|
|
|
|
func latestAvailabilityRoots(
|
|
roots []outbound.AssessmentRootAvailabilitySummary,
|
|
target domain.GradeCode,
|
|
) (*outbound.AssessmentRootAvailabilitySummary, *outbound.AssessmentRootAvailabilitySummary) {
|
|
var latest *outbound.AssessmentRootAvailabilitySummary
|
|
var latestSameGrade *outbound.AssessmentRootAvailabilitySummary
|
|
for index := range roots {
|
|
root := &roots[index]
|
|
if latest == nil || root.RootCreatedAt.After(latest.RootCreatedAt) {
|
|
latest = root
|
|
}
|
|
if root.RootTargetGrade == target &&
|
|
(latestSameGrade == nil || root.RootCreatedAt.After(latestSameGrade.RootCreatedAt)) {
|
|
latestSameGrade = root
|
|
}
|
|
}
|
|
return latest, latestSameGrade
|
|
}
|
|
|
|
func sameGradeAvailabilityCooldown(
|
|
blockedUntil time.Time,
|
|
latestSameGrade *outbound.AssessmentRootAvailabilitySummary,
|
|
policy domain.AssessmentPolicy,
|
|
now time.Time,
|
|
) time.Time {
|
|
if latestSameGrade != nil {
|
|
updatedAt := effectiveAvailabilityUpdatedAt(latestSameGrade.RootState, latestSameGrade.RootUpdatedAt, latestSameGrade.RootExpiresAt, now)
|
|
blockedUntil = laterAvailability(blockedUntil, updatedAt.Add(policy.SameGradeRetryAfter.Duration()), now)
|
|
}
|
|
return blockedUntil
|
|
}
|
|
|
|
func latestRootAvailabilityCooldown(
|
|
blockedUntil time.Time,
|
|
latest *outbound.AssessmentRootAvailabilitySummary,
|
|
target domain.GradeCode,
|
|
policy domain.AssessmentPolicy,
|
|
now time.Time,
|
|
) time.Time {
|
|
if latest != nil {
|
|
lastUpdatedAt := effectiveAvailabilityUpdatedAt(latest.LatestState, latest.LatestUpdatedAt, latest.LatestExpiresAt, now)
|
|
platformFailure := latest.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
|
|
isPlatformAttemptFailure(latest.LatestPlatformError)
|
|
if !platformFailure &&
|
|
availabilityCorrectionWindowOpen(latest, now) {
|
|
blockedUntil = laterAvailability(blockedUntil, latest.LatestChainDeadline, now)
|
|
}
|
|
if !platformFailure && gradeRank(target) > gradeRank(latest.LatestTargetGrade) {
|
|
blockedUntil = laterAvailability(blockedUntil, lastUpdatedAt.Add(policy.PromotionMinInterval.Duration()), now)
|
|
}
|
|
}
|
|
return blockedUntil
|
|
}
|
|
|
|
func effectiveAvailabilityUpdatedAt(
|
|
state domain.AssessmentAttemptState,
|
|
updatedAt, expiresAt, now time.Time,
|
|
) time.Time {
|
|
if isAssessmentAttemptActiveState(state) && !expiresAt.After(now) {
|
|
// A read-only preflight may notice expiry after the deadline. Use the
|
|
// attempt's fixed deadline as the transition time so polling cannot
|
|
// extend the retry interval.
|
|
return expiresAt
|
|
}
|
|
return updatedAt
|
|
}
|
|
|
|
func availabilityCorrectionWindowOpen(root *outbound.AssessmentRootAvailabilitySummary, now time.Time) bool {
|
|
if !root.LatestChainDeadline.After(root.RootCreatedAt) || !now.Before(root.LatestChainDeadline) {
|
|
return false
|
|
}
|
|
if root.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
|
|
isPlatformAttemptFailure(root.LatestPlatformError) {
|
|
return false
|
|
}
|
|
switch root.LatestState {
|
|
case domain.AssessmentAttemptStateInProgress,
|
|
domain.AssessmentAttemptStatePracticePending,
|
|
domain.AssessmentAttemptStateAdditionalPracticePending,
|
|
domain.AssessmentAttemptStateReadyToFinalize:
|
|
// The GET does not write the expiry transition. An expired active
|
|
// attempt still holds its correction chain until the immutable chain
|
|
// deadline, matching the POST path that records expiry at expires_at.
|
|
return !root.LatestExpiresAt.After(now) && root.LatestOutcome == ""
|
|
case domain.AssessmentAttemptStateInsufficientBank:
|
|
return false
|
|
case domain.AssessmentAttemptStateExpired:
|
|
return root.LatestOutcome == ""
|
|
case domain.AssessmentAttemptStateCompleted:
|
|
return root.LatestOutcome == domain.AssessmentAttemptOutcomeNotConfirmed ||
|
|
root.LatestOutcome == domain.AssessmentAttemptOutcomeNotDetermined
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isAssessmentAttemptActiveState(state domain.AssessmentAttemptState) bool {
|
|
switch state {
|
|
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
|
|
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
|
|
return true
|
|
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
|
|
domain.AssessmentAttemptStateInsufficientBank:
|
|
return false
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isPlatformAttemptFailure(reason string) bool {
|
|
return reason == "insufficient_bank" || reason == "sandbox_unavailable"
|
|
}
|
|
|
|
func laterAvailability(current, candidate, now time.Time) time.Time {
|
|
if !candidate.After(now) {
|
|
return current
|
|
}
|
|
if current.IsZero() || candidate.After(current) {
|
|
return candidate
|
|
}
|
|
return current
|
|
}
|