package assessment import ( "context" cryptorand "crypto/rand" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "math/big" "slices" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) const ( createAttemptOperation = "assessment_attempt.create" startSessionOperation = "assessment_attempt.session" maxAttemptIdempotencyKeyBytes = 255 maxAttemptCanonicalBodyBytes = 1 << 20 attemptAlgorithmVersion = "assessment.v1" attemptVariantLimit = 100 ) var ( ErrAttemptForbidden = errors.New("assessment attempt operation forbidden") ErrAttemptEmailNotVerified = errors.New("assessment attempt requires a confirmed email") ErrAttemptConsentRequired = errors.New("automated assessment consent is required") ErrInvalidAttemptRequest = errors.New("invalid assessment attempt request") ErrInvalidAttemptKey = errors.New("invalid assessment attempt idempotency key") ErrAttemptKeyReused = errors.New("assessment attempt idempotency key was reused") ErrAttemptNotFound = errors.New("assessment attempt not found") ErrAttemptVersionConflict = errors.New("assessment attempt version changed") ErrAttemptStateConflict = errors.New("assessment attempt state does not allow this command") ) // Keyring computes scoped idempotency digests with the server's shared secret. type Keyring interface { IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte } // AttemptFieldError names a request field without retaining or echoing its value. type AttemptFieldError struct { Pointer string Reason string } func (fieldError *AttemptFieldError) Error() string { return "assessment attempt field " + fieldError.Pointer + " " + fieldError.Reason } func (fieldError *AttemptFieldError) Unwrap() error { return ErrInvalidAttemptRequest } // AttemptService creates, reads, and resumes candidate-owned attempts. type AttemptService struct { transactor outbound.Transactor snapshotExecutor outbound.ReadOnlySnapshotTransactor keyring Keyring clock func() time.Time } // NewAttemptService fails at startup when a required dependency is missing. func NewAttemptService( transactor outbound.Transactor, snapshotExecutor outbound.ReadOnlySnapshotTransactor, keyring Keyring, clock func() time.Time, ) (*AttemptService, error) { if transactor == nil || snapshotExecutor == nil || keyring == nil || clock == nil { return nil, errors.New("assessment.NewAttemptService - every dependency must be set") } return &AttemptService{ transactor: transactor, snapshotExecutor: snapshotExecutor, keyring: keyring, clock: clock, }, nil } // CreateAttemptCommand is one of the three disjoint public request shapes. // All values are private candidate data and must not be logged. type CreateAttemptCommand struct { ActorID uuid.UUID IdempotencyKey string Kind domain.AssessmentAttemptKind Specialization *domain.SpecializationCode TargetGrade *domain.GradeCode TaskLanguage *domain.TaskLanguageCode RootAttemptID domain.AssessmentAttemptID } type canonicalAttemptCreateBody struct { Kind domain.AssessmentAttemptKind `json:"kind"` Specialization *domain.SpecializationCode `json:"specialization"` TargetGrade *domain.GradeCode `json:"target_grade"` TaskLanguage *domain.TaskLanguageCode `json:"task_language"` RootAttemptID string `json:"root_attempt_id,omitempty"` } // CreateAttempt returns the immutable 201 or 409 response retained for the // idempotency window. Request validation errors roll back the reservation. func (service *AttemptService) CreateAttempt( ctx context.Context, command CreateAttemptCommand, ) (outbound.AssessmentAttemptCreateResult, error) { const location = "AttemptService.CreateAttempt" body, err := canonicalizeAttemptCreateBody(command) if err != nil { return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - validate request: %w", location, err) } keyTime, err := assessmentIdempotencyTime(service.clock()) if err != nil { return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - validate application time: %w", location, err) } var result outbound.AssessmentAttemptCreateResult err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { return err } request, err := service.prepareAttemptIdempotency(createAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime) if err != nil { return fmt.Errorf("%s - prepare idempotency: %w", location, err) } stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) if err != nil { return fmt.Errorf("%s - reserve idempotency: %w", location, err) } attempts := unit.AssessmentAttempts() if !created { if stored.Fingerprint != request.record.Fingerprint { return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) } outcome, err := attempts.GetCreateOutcome(ctx, request.scope) if err != nil { return fmt.Errorf("%s - read immutable create response: %w", location, err) } result = outbound.AssessmentAttemptCreateResult{Outcome: outcome, Replayed: true} return nil } if err := attempts.DeleteExpiredOutcome(ctx, request.scope); err != nil { return fmt.Errorf("%s - remove expired create response: %w", location, err) } outcome, err := service.createAttemptInTransaction(ctx, unit, command) if err != nil { return err } if err := attempts.SaveCreateOutcome(ctx, request.scope, outcome); err != nil { return fmt.Errorf("%s - store immutable create response: %w", location, err) } result = outbound.AssessmentAttemptCreateResult{Outcome: outcome} return nil }) if err != nil { return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } func (service *AttemptService) createAttemptInTransaction( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (outbound.AssessmentAttemptCreateOutcome, error) { if command.Kind == domain.AssessmentAttemptKindDemoExpress { return service.createTrainingAttempt(ctx, unit, command) } return service.createRealAttempt(ctx, unit, command) } func (service *AttemptService) createRealAttempt( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (outbound.AssessmentAttemptCreateOutcome, error) { const location = "AttemptService.createRealAttempt" if err := lockRealAttemptScope(ctx, unit, command); err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - lock C3 and candidate scope: %w", location, err) } policyVersion, err := effectiveAttemptPolicy(ctx, unit) if errors.Is(err, outbound.ErrPolicyVersionNotFound) { return assessmentConflictOutcome(), nil } if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read effective product policy after scope lock: %w", location, err) } policy := policyVersion.Policy().Assessment if policy.Attempt == nil { return assessmentConflictOutcome(), nil } if policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic { return assessmentConflictOutcome(), nil } selection, available, err := resolveRealAttemptSelection(ctx, unit, command, policyVersion) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - resolve current bank selection: %w", location, err) } if !available { return assessmentConflictOutcome(), nil } databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read database time after locks: %w", location, err) } databaseTime = databaseTime.UTC().Truncate(time.Microsecond) if err := validateRealAttemptAvailability(ctx, unit, command, policy, databaseTime); err != nil { if selectionIsUnavailable(err) || errors.Is(err, outbound.ErrAssessmentAttemptConflict) { return assessmentConflictOutcome(), nil } return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - validate current availability: %w", location, err) } return service.persistRealAttempt(ctx, unit, command, policyVersion, policy, databaseTime, selection) } func resolveRealAttemptSelection( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, policyVersion domain.PolicyVersion, ) (outbound.AssessmentBankSelection, bool, error) { if _, err := validateCandidateAssessmentSelection(ctx, unit, command); err != nil { return outbound.AssessmentBankSelection{}, false, fmt.Errorf("validate candidate selection: %w", err) } active, _, err := activeRealAttemptBlocksCreation(ctx, unit, command) if err != nil { return outbound.AssessmentBankSelection{}, false, fmt.Errorf("check active attempt: %w", err) } if active { return outbound.AssessmentBankSelection{}, false, nil } selection, err := unit.AssessmentBank().ResolveCurrentSelection( ctx, *command.Specialization, *command.TargetGrade, command.TaskLanguage, ) if err != nil { if selectionIsUnavailable(err) { return outbound.AssessmentBankSelection{}, false, nil } return outbound.AssessmentBankSelection{}, false, err } if selection.ProductPolicyVersionID != policyVersion.ID() || selection.ProductPolicyVersion != policyVersion.Version() { return outbound.AssessmentBankSelection{}, false, nil } return selection, true, nil } func lockRealAttemptScope(ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand) error { const location = "AttemptService.lockRealAttemptScope" if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil { if errors.Is(err, outbound.ErrConsentNotFound) { return fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptConsentRequired) } return fmt.Errorf("%s - lock current C3 consent: %w", location, err) } if err := unit.AssessmentAttempts().LockScope(ctx, command.ActorID, command.Specialization); err != nil { return fmt.Errorf("%s - lock candidate quota and track: %w", location, err) } return nil } func activeRealAttemptBlocksCreation( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (bool, time.Time, error) { const location = "AttemptService.activeRealAttemptBlocksCreation" repository := unit.AssessmentAttempts() active, found, err := repository.GetActiveForSpecialization(ctx, command.ActorID, *command.Specialization) if err != nil { return false, time.Time{}, err } databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return false, time.Time{}, fmt.Errorf("%s - read database time after active row lock: %w", location, err) } databaseTime = databaseTime.UTC().Truncate(time.Microsecond) if !found { return false, databaseTime, nil } if active.ExpiresAt().After(databaseTime) { return true, databaseTime, nil } if _, _, err := repository.StartOrResumeSession(ctx, command.ActorID, active.ID(), active.Version(), active.ExpiresAt()); err != nil { return false, time.Time{}, fmt.Errorf("%s - expire due active attempt: %w", location, err) } _, found, err = repository.GetActiveForSpecialization(ctx, command.ActorID, *command.Specialization) if err != nil { return false, time.Time{}, err } return found, databaseTime, nil } func validateRealAttemptAvailability( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, policy domain.AssessmentPolicy, now time.Time, ) error { if _, err := validateCurrentAssessmentSelection(ctx, unit, command); err != nil { return err } if command.Kind == domain.AssessmentAttemptKindRoot { return checkRootAttemptAvailability(ctx, unit, command, policy, now) } return nil } func (service *AttemptService) persistRealAttempt( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, policyVersion domain.PolicyVersion, policy domain.AssessmentPolicy, databaseTime time.Time, selection outbound.AssessmentBankSelection, ) (outbound.AssessmentAttemptCreateOutcome, error) { const location = "AttemptService.persistRealAttempt" itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems items, err := generatedAssessmentItems(selection.Families, itemCount) if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) { return assessmentConflictOutcome(), nil } if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - generate frozen items: %w", location, err) } chain, err := loadCorrectionChain(ctx, unit.AssessmentAttempts(), command) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read correction chain: %w", location, err) } attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ UserID: command.ActorID, Kind: command.Kind, BankCategory: selection.Opening.Category, Specialization: command.Specialization, TargetGrade: command.TargetGrade, TaskLanguage: command.TaskLanguage, Chain: chain, Versions: realAttemptVersions(policyVersion, selection), Policy: policyVersion, CreatedAt: databaseTime, Items: items, }) if err != nil { if errors.Is(err, domain.ErrInvalidAssessmentAttempt) { return outbound.AssessmentAttemptCreateOutcome{}, attemptFieldError("/target_grade", "does not continue the requested assessment track") } return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - construct attempt: %w", location, err) } if err := unit.AssessmentAttempts().Create(ctx, attempt); err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - persist attempt and frozen items: %w", location, err) } return outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: attempt.PublicSnapshot()}, nil } func loadCorrectionChain( ctx context.Context, repository outbound.AssessmentAttemptRepository, command CreateAttemptCommand, ) ([]domain.AssessmentAttempt, error) { if command.Kind != domain.AssessmentAttemptKindCorrective { return nil, nil } chain, err := repository.ListCorrectionChain(ctx, command.ActorID, *command.Specialization, command.RootAttemptID) if err != nil { return nil, err } if len(chain) == 0 { return nil, attemptFieldError("/root_attempt_id", "must identify an eligible attempt chain") } return chain, nil } func selectionIsUnavailable(err error) bool { return errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) || errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous) } func (service *AttemptService) createTrainingAttempt( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (outbound.AssessmentAttemptCreateOutcome, error) { const location = "AttemptService.createTrainingAttempt" if err := unit.AssessmentAttempts().LockScope(ctx, command.ActorID, nil); err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - lock candidate training scope: %w", location, err) } policyVersion, err := effectiveAttemptPolicy(ctx, unit) if errors.Is(err, outbound.ErrPolicyVersionNotFound) { return assessmentConflictOutcome(), nil } if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read effective product policy after scope lock: %w", location, err) } training := policyVersion.Policy().Assessment.Training if training == nil { return assessmentConflictOutcome(), nil } selection, available, err := resolveTrainingAttemptSelection(ctx, unit, command.ActorID, policyVersion, training) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - resolve reviewed training bank: %w", location, err) } if !available { return assessmentConflictOutcome(), nil } databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read database time after locks: %w", location, err) } databaseTime = databaseTime.UTC().Truncate(time.Microsecond) items, err := generatedAssessmentItems(selection.Families, training.DemoExpressItemCount) if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) { return assessmentConflictOutcome(), nil } if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - generate frozen training items: %w", location, err) } attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ UserID: command.ActorID, Kind: domain.AssessmentAttemptKindDemoExpress, BankCategory: selection.Category, Versions: trainingAttemptVersions(policyVersion, selection), Policy: policyVersion, CreatedAt: databaseTime, Items: items, }) if err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - construct training attempt: %w", location, err) } if err := unit.AssessmentAttempts().Create(ctx, attempt); err != nil { return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - persist training attempt and frozen items: %w", location, err) } return outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: attempt.PublicSnapshot()}, nil } func resolveTrainingAttemptSelection( ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, policyVersion domain.PolicyVersion, training *domain.AssessmentTrainingPolicy, ) (outbound.AssessmentTrainingBankSelection, bool, error) { active, _, err := activeTrainingAttemptBlocksCreation(ctx, unit, userID) if err != nil { return outbound.AssessmentTrainingBankSelection{}, false, fmt.Errorf("check active training attempt: %w", err) } if active { return outbound.AssessmentTrainingBankSelection{}, false, nil } selection, err := unit.AssessmentBank().ResolveCurrentTrainingSelection(ctx, policyVersion.ID(), policyVersion.Version()) if err != nil { if selectionIsUnavailable(err) { return outbound.AssessmentTrainingBankSelection{}, false, nil } return outbound.AssessmentTrainingBankSelection{}, false, err } if selection.ProductPolicyVersionID != policyVersion.ID() || selection.ProductPolicyVersion != policyVersion.Version() || len(selection.Families) < int(training.DemoExpressItemCount) { return outbound.AssessmentTrainingBankSelection{}, false, nil } return selection, true, nil } func activeTrainingAttemptBlocksCreation( ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, ) (bool, time.Time, error) { const location = "AttemptService.activeTrainingAttemptBlocksCreation" repository := unit.AssessmentAttempts() active, found, err := repository.GetActiveTraining(ctx, userID) if err != nil { return false, time.Time{}, err } databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return false, time.Time{}, fmt.Errorf("%s - read database time after active row lock: %w", location, err) } databaseTime = databaseTime.UTC().Truncate(time.Microsecond) if !found { return false, databaseTime, nil } if active.ExpiresAt().After(databaseTime) { return true, databaseTime, nil } if _, _, err := repository.StartOrResumeSession(ctx, userID, active.ID(), active.Version(), databaseTime); err != nil { return false, time.Time{}, fmt.Errorf("%s - expire due attempt: %w", location, err) } _, found, err = repository.GetActiveTraining(ctx, userID) if err != nil { return false, time.Time{}, err } return found, databaseTime, nil } // GetMyAttempt reads only the owner's current public projection. It never // starts a session or commits an expiry transition. func (service *AttemptService) GetMyAttempt( ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, ) (domain.AssessmentAttemptPublicSnapshot, error) { const location = "AttemptService.GetMyAttempt" if userID == uuid.Nil || attemptID.IsZero() { return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden) } var result domain.AssessmentAttemptPublicSnapshot err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil { return err } attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID) if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { return fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound) } if err != nil { return fmt.Errorf("%s - read owner-scoped attempt: %w", location, err) } result = attempt.PublicSnapshot() return nil }) if err != nil { return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } type StartAttemptSessionCommand struct { ActorID uuid.UUID AttemptID domain.AssessmentAttemptID ExpectedVersion int64 IdempotencyKey string } type canonicalAttemptSessionBody struct { AttemptID string `json:"attempt_id"` ExpectedVersion int64 `json:"expected_version"` } // StartSession returns the immutable response captured for this session key. func (service *AttemptService) StartSession( ctx context.Context, command StartAttemptSessionCommand, ) (outbound.AssessmentAttemptSessionResult, error) { const location = "AttemptService.StartSession" if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - candidate, attempt, and expected version are required: %w", location, ErrInvalidAttemptRequest) } body, err := json.Marshal(canonicalAttemptSessionBody{AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion}) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - encode request fingerprint: %w", location, ErrInvalidAttemptRequest) } keyTime, err := assessmentIdempotencyTime(service.clock()) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - validate application time: %w", location, err) } var result outbound.AssessmentAttemptSessionResult err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var transactionErr error result, transactionErr = service.startSessionInTransaction(ctx, unit, command, body, keyTime) return transactionErr }) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } func (service *AttemptService) startSessionInTransaction( ctx context.Context, unit outbound.UnitOfWork, command StartAttemptSessionCommand, body []byte, keyTime time.Time, ) (outbound.AssessmentAttemptSessionResult, error) { const location = "AttemptService.startSessionInTransaction" if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { return outbound.AssessmentAttemptSessionResult{}, err } request, err := service.prepareAttemptIdempotency(startSessionOperation, command.IdempotencyKey, command.ActorID, body, keyTime) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err) } stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - reserve idempotency: %w", location, err) } if !created { return replaySessionOutcome(ctx, unit.AssessmentAttempts(), request, stored) } return service.startNewSession(ctx, unit, command, request) } func replaySessionOutcome( ctx context.Context, repository outbound.AssessmentAttemptRepository, request attemptIdempotencyRequest, stored outbound.IdempotencyRecord, ) (outbound.AssessmentAttemptSessionResult, error) { const location = "assessment.replaySessionOutcome" if stored.Fingerprint != request.record.Fingerprint { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) } response, err := repository.GetSessionOutcome(ctx, request.scope) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read immutable session response: %w", location, err) } return outbound.AssessmentAttemptSessionResult{Response: response, Replayed: true}, nil } func (service *AttemptService) startNewSession( ctx context.Context, unit outbound.UnitOfWork, command StartAttemptSessionCommand, request attemptIdempotencyRequest, ) (outbound.AssessmentAttemptSessionResult, error) { const location = "AttemptService.startNewSession" repository := unit.AssessmentAttempts() if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - remove expired session response: %w", location, err) } kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID) if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound) } if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) } if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - authorize session: %w", location, err) } current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID) if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound) } if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) } if current.Kind() != kind { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) } databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read database time after attempt lock: %w", location, err) } updated, _, err := repository.StartOrResumeSession(ctx, command.ActorID, command.AttemptID, command.ExpectedVersion, databaseTime) if errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict) || errors.Is(err, domain.ErrAssessmentAttemptVersionConflict) { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict) } if err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - start or resume session: %w", location, err) } response := updated.PublicSnapshot() if err := repository.SaveSessionOutcome(ctx, request.scope, response); err != nil { return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - store immutable session response: %w", location, err) } return outbound.AssessmentAttemptSessionResult{Response: response}, nil } func lockSessionConsent( ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, kind domain.AssessmentAttemptKind, ) error { const location = "assessment.lockSessionConsent" if kind == domain.AssessmentAttemptKindDemoExpress { return nil } if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, actorID, domain.ConsentPurposeAutoCategorization); err != nil { if errors.Is(err, outbound.ErrConsentNotFound) { return fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptConsentRequired) } return fmt.Errorf("%s - lock current C3 consent: %w", location, err) } return nil } type attemptIdempotencyRequest struct { scope outbound.AssessmentAttemptIdempotencyScope record outbound.IdempotencyRecord } func (service *AttemptService) prepareAttemptIdempotency( operation string, key string, actorID uuid.UUID, body []byte, now time.Time, ) (attemptIdempotencyRequest, error) { if !validAttemptIdempotencyKey(key) { return attemptIdempotencyRequest{}, ErrInvalidAttemptKey } if len(body) == 0 || len(body) > maxAttemptCanonicalBodyBytes { return attemptIdempotencyRequest{}, ErrInvalidAttemptRequest } expiresAt := now.Add(outbound.IdempotencyRetention) if expiresAt.Year() > 9999 || !expiresAt.After(now) { return attemptIdempotencyRequest{}, ErrInvalidAttemptRequest } scopeBytes := service.keyring.IdempotencyScope(operation, key, actorID.String()) fingerprint := service.keyring.Fingerprint(body) scope := outbound.AssessmentAttemptIdempotencyScope(scopeBytes) record := outbound.IdempotencyRecord{ Scope: scopeBytes, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt, } return attemptIdempotencyRequest{scope: scope, record: record}, nil } func canonicalizeAttemptCreateBody(command CreateAttemptCommand) ([]byte, error) { if command.ActorID == uuid.Nil { return nil, ErrAttemptForbidden } body := canonicalAttemptCreateBody{Kind: command.Kind} switch command.Kind { case domain.AssessmentAttemptKindRoot: if !validRealCreateTrack(command) || !command.RootAttemptID.IsZero() { return nil, ErrInvalidAttemptRequest } body.Specialization, body.TargetGrade, body.TaskLanguage = command.Specialization, command.TargetGrade, command.TaskLanguage case domain.AssessmentAttemptKindCorrective: if !validRealCreateTrack(command) || command.RootAttemptID.IsZero() { return nil, ErrInvalidAttemptRequest } body.Specialization, body.TargetGrade, body.TaskLanguage = command.Specialization, command.TargetGrade, command.TaskLanguage rootID := command.RootAttemptID.String() body.RootAttemptID = rootID case domain.AssessmentAttemptKindDemoExpress: if command.Specialization != nil || command.TargetGrade != nil || command.TaskLanguage != nil || !command.RootAttemptID.IsZero() { return nil, ErrInvalidAttemptRequest } default: return nil, ErrInvalidAttemptRequest } encoded, err := json.Marshal(body) if err != nil || len(encoded) > maxAttemptCanonicalBodyBytes { return nil, ErrInvalidAttemptRequest } return encoded, nil } func validRealCreateTrack(command CreateAttemptCommand) bool { return command.Specialization != nil && command.Specialization.IsKnown() && command.TargetGrade != nil && command.TargetGrade.IsKnown() && (command.TaskLanguage == nil || command.TaskLanguage.IsKnown()) } func validAttemptIdempotencyKey(value string) bool { if len(value) == 0 || len(value) > maxAttemptIdempotencyKeyBytes { return false } for index := range len(value) { character := value[index] if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || character >= '0' && character <= '9' || character == '.' || character == '_' || character == ':' || character == '-' { continue } return false } return true } func assessmentIdempotencyTime(value time.Time) (time.Time, error) { now := value.UTC().Truncate(time.Microsecond) if now.IsZero() || now.Year() < 1 || now.Year() > 9999 { return time.Time{}, ErrInvalidAttemptRequest } return now, nil } func requireAttemptCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error { if userID == uuid.Nil { return fmt.Errorf("%s - candidate ID is required: %w", location, ErrAttemptForbidden) } user, err := unit.Users().GetByID(ctx, userID) if err != nil { if errors.Is(err, outbound.ErrUserNotFound) { return fmt.Errorf("%s - candidate account is missing: %w", location, ErrAttemptForbidden) } return fmt.Errorf("%s - read candidate account: %w", location, err) } if !user.EmailVerified() { return fmt.Errorf("%s - require confirmed email: %w", location, ErrAttemptEmailNotVerified) } if user.Scenario != domain.ScenarioCandidate { return fmt.Errorf("%s - require candidate scenario: %w", location, ErrAttemptForbidden) } return nil } func validateCandidateAssessmentSelection( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (domain.CandidateQuestionnaire, error) { questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, command.ActorID) if err != nil { return domain.CandidateQuestionnaire{}, fmt.Errorf("read candidate questionnaire: %w", err) } for _, answer := range questionnaire.Specializations() { if answer.Specialization != *command.Specialization { continue } if command.TaskLanguage != nil && !slices.Contains(answer.TaskLanguages, *command.TaskLanguage) { return domain.CandidateQuestionnaire{}, attemptFieldError("/task_language", "must be one of the candidate's selected task languages") } return questionnaire, nil } return domain.CandidateQuestionnaire{}, attemptFieldError("/specialization", "must be present in the candidate questionnaire") } func validateCurrentAssessmentSelection( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, ) (domain.SpecializationAvailability, error) { availability, err := unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx) if err != nil { return domain.SpecializationAvailability{}, fmt.Errorf("read current specialization catalog: %w", err) } for _, current := range availability { if current.Specialization != *command.Specialization { continue } if !slices.Contains(current.Grades, *command.TargetGrade) { return domain.SpecializationAvailability{}, attemptFieldError("/target_grade", "is not offered by the current published bank") } if command.TaskLanguage == nil && len(current.TaskLanguages) > 0 { return domain.SpecializationAvailability{}, attemptFieldError("/task_language", "must be selected from the current published bank") } if command.TaskLanguage != nil && !slices.Contains(current.TaskLanguages, *command.TaskLanguage) { return domain.SpecializationAvailability{}, attemptFieldError("/task_language", "is not offered by the current published bank") } return current, nil } return domain.SpecializationAvailability{}, outbound.ErrAssessmentSelectionUnavailable } func effectiveAttemptPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.PolicyVersion, error) { databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return domain.PolicyVersion{}, fmt.Errorf("read database time: %w", err) } policy, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime) if err != nil { return domain.PolicyVersion{}, err } return policy, nil } func checkRootAttemptAvailability( ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand, policy domain.AssessmentPolicy, now time.Time, ) error { const location = "AttemptService.checkRootAttemptAvailability" if policy.Attempt == nil || command.Specialization == nil || command.TargetGrade == nil { return fmt.Errorf("%s - explicit policy and track are required: %w", location, outbound.ErrAssessmentAttemptConflict) } repository := unit.AssessmentAttempts() if err := checkLatestRootAvailability(ctx, repository, command, policy, now); err != nil { return fmt.Errorf("%s - check latest root: %w", location, err) } if err := checkSameGradeRootAvailability(ctx, repository, command, policy, now); err != nil { return fmt.Errorf("%s - check same-grade retry: %w", location, err) } return checkRootQuota(ctx, repository, command.ActorID, policy, now) } func checkLatestRootAvailability( ctx context.Context, repository outbound.AssessmentAttemptRepository, command CreateAttemptCommand, policy domain.AssessmentPolicy, now time.Time, ) error { const location = "assessment.checkLatestRootAvailability" latest, found, err := repository.GetLatestRootForSpecialization(ctx, command.ActorID, *command.Specialization, nil) if err != nil || !found { return err } chain, err := repository.ListCorrectionChain(ctx, command.ActorID, *command.Specialization, latest.ID()) if err != nil { return err } if len(chain) == 0 { return fmt.Errorf("%s - root chain is missing its root: %w", location, domain.ErrInvalidAssessmentAttempt) } last := chain[len(chain)-1] platformFailure, err := attemptHasPlatformFailure(ctx, repository, last) if err != nil { return fmt.Errorf("%s - inspect latest attempt result: %w", location, err) } if platformFailure { return nil } if hasOpenCorrectionWindow(chain, now) { return fmt.Errorf("%s - a correction chain remains open: %w", location, outbound.ErrAssessmentAttemptConflict) } if isPromotionTooSoon(last, *command.TargetGrade, policy.PromotionMinInterval.Duration(), now) { return fmt.Errorf("%s - promotion interval has not elapsed: %w", location, outbound.ErrAssessmentAttemptConflict) } return nil } func attemptHasPlatformFailure( ctx context.Context, repository outbound.AssessmentAttemptRepository, attempt domain.AssessmentAttempt, ) (bool, error) { if attempt.State() == domain.AssessmentAttemptStateInsufficientBank { return true, nil } if attempt.State() != domain.AssessmentAttemptStateCompleted { return false, nil } result, err := repository.GetResult(ctx, attempt.Snapshot().UserID, attempt.ID()) if err != nil { return false, err } return isPlatformAttemptFailure(result.NotDeterminedReason), nil } func hasOpenCorrectionWindow(chain []domain.AssessmentAttempt, now time.Time) bool { return eligibleCorrectionWindow(chain[len(chain)-1]) && now.Before(chain[0].ChainDeadline()) } func isPromotionTooSoon(last domain.AssessmentAttempt, target domain.GradeCode, interval time.Duration, now time.Time) bool { current := last.Snapshot().TargetGrade return current != nil && gradeRank(target) > gradeRank(*current) && now.Before(last.UpdatedAt().Add(interval)) } func checkSameGradeRootAvailability( ctx context.Context, repository outbound.AssessmentAttemptRepository, command CreateAttemptCommand, policy domain.AssessmentPolicy, now time.Time, ) error { const location = "assessment.checkSameGradeRootAvailability" latest, found, err := repository.GetLatestRootForSpecialization(ctx, command.ActorID, *command.Specialization, command.TargetGrade) if err != nil || !found { return err } if now.Before(latest.UpdatedAt().Add(policy.SameGradeRetryAfter.Duration())) { return fmt.Errorf("%s - same-grade retry interval has not elapsed: %w", location, outbound.ErrAssessmentAttemptConflict) } return nil } func checkRootQuota( ctx context.Context, repository outbound.AssessmentAttemptRepository, userID uuid.UUID, policy domain.AssessmentPolicy, now time.Time, ) error { const location = "assessment.checkRootQuota" since := now.Add(-policy.AttemptWindow.Duration()) count, err := repository.CountRootAttemptsSince(ctx, userID, nil, since) if err != nil { return fmt.Errorf("%s - count global root quota: %w", location, err) } if count >= policy.MaxAttemptsPerWindow { return fmt.Errorf("%s - global root quota is exhausted: %w", location, outbound.ErrAssessmentAttemptConflict) } return nil } func eligibleCorrectionWindow(attempt domain.AssessmentAttempt) bool { snapshot := attempt.Snapshot() if !snapshot.ChainDeadline.After(snapshot.CreatedAt) { return false } switch snapshot.State { case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending, domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize, domain.AssessmentAttemptStateInsufficientBank: return false case domain.AssessmentAttemptStateExpired: return snapshot.Outcome == "" case domain.AssessmentAttemptStateCompleted: return snapshot.Outcome == domain.AssessmentAttemptOutcomeNotConfirmed || snapshot.Outcome == domain.AssessmentAttemptOutcomeNotDetermined default: return false } } func gradeRank(grade domain.GradeCode) int { switch grade { case domain.GradeIntern: return 0 case domain.GradeJunior: return 1 case domain.GradeMiddle: return 2 case domain.GradeSenior: return 3 default: return -1 } } func generatedAssessmentItems( families []domain.AssessmentFamily, count int32, ) ([]domain.AssessmentAttemptItemInput, error) { if count < 1 || count > attemptVariantLimit || len(families) < int(count) { return nil, outbound.ErrAssessmentSelectionUnavailable } selected := slices.Clone(families) for index := len(selected) - 1; index > 0; index-- { bound := big.NewInt(int64(index + 1)) choice, err := cryptorand.Int(cryptorand.Reader, bound) if err != nil { return nil, fmt.Errorf("generatedAssessmentItems - choose family: %w", err) } selectedIndex := int(choice.Int64()) selected[index], selected[selectedIndex] = selected[selectedIndex], selected[index] } items := make([]domain.AssessmentAttemptItemInput, 0, count) for _, family := range selected[:int(count)] { var seedBytes [8]byte if _, err := cryptorand.Read(seedBytes[:]); err != nil { return nil, fmt.Errorf("generatedAssessmentItems - generate variant seed: %w", err) } variant, err := family.NewVariant(domain.VariantSeed(binary.LittleEndian.Uint64(seedBytes[:]))) if err != nil { return nil, fmt.Errorf("generatedAssessmentItems - generate frozen variant: %w", err) } items = append(items, domain.AssessmentAttemptItemInput{Variant: variant}) } return items, nil } func realAttemptVersions( policy domain.PolicyVersion, selection outbound.AssessmentBankSelection, ) domain.AssessmentAttemptVersions { return domain.AssessmentAttemptVersions{ ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), GradingPolicyVersionID: selection.Opening.PolicyVersionID, OpeningID: selection.Opening.ID, OpeningManifestHash: selection.ManifestSHA, BankVersion: "bank." + hex.EncodeToString(selection.ManifestSHA[:12]), AlgorithmVersion: attemptAlgorithmVersion, } } func trainingAttemptVersions( policy domain.PolicyVersion, selection outbound.AssessmentTrainingBankSelection, ) domain.AssessmentAttemptVersions { return domain.AssessmentAttemptVersions{ ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), TrainingBindingID: selection.BindingID, TrainingManifestHash: selection.ManifestSHA, BankVersion: "training." + hex.EncodeToString(selection.ManifestSHA[:12]), AlgorithmVersion: attemptAlgorithmVersion, } } func assessmentConflictOutcome() outbound.AssessmentAttemptCreateOutcome { return outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"} } func attemptFieldError(pointer, reason string) error { return &AttemptFieldError{Pointer: pointer, Reason: reason} } func storeAttemptCommandProblem( ctx context.Context, repository outbound.AssessmentAttemptRepository, scope outbound.AssessmentAttemptIdempotencyScope, operation string, statusCode int16, result *outbound.AssessmentAttemptCommandResult, ) error { const location = "assessment.storeAttemptCommandProblem" problemCode, allowed := assessmentAttemptProblemCode(statusCode) if !allowed { return fmt.Errorf("%s - problem status is not allowlisted", location) } outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: statusCode, ProblemCode: problemCode} switch operation { case "answer": if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil { return fmt.Errorf("%s - store answer problem outcome: %w", location, err) } case "finalize": if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { return fmt.Errorf("%s - store finalize problem outcome: %w", location, err) } default: return fmt.Errorf("%s - operation is not allowlisted", location) } *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} return nil } func assessmentAttemptProblemCode(statusCode int16) (string, bool) { switch statusCode { case 404: return "not_found", true case 409: return "state_conflict", true default: return "", false } } func storeFinalizePendingItems( ctx context.Context, repository outbound.AssessmentAttemptRepository, scope outbound.AssessmentAttemptIdempotencyScope, itemIDs []uuid.UUID, result *outbound.AssessmentAttemptCommandResult, ) error { const location = "assessment.storeFinalizePendingItems" if len(itemIDs) == 0 || len(itemIDs) > 220 { return fmt.Errorf("%s - pending item list is outside its bound", location) } outcome := outbound.AssessmentAttemptCommandOutcome{ StatusCode: 409, ProblemCode: "state_conflict", PendingItemIDs: append([]uuid.UUID{}, itemIDs...), } if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { return fmt.Errorf("%s - store finalize conflict: %w", location, err) } *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} return nil }