Files

478 lines
20 KiB
Go

package assessment
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const finalizeAttemptOperation = "assessment_attempt.finalize"
type FinalizeAssessmentAttemptCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
ExpectedVersion int64
IdempotencyKey string
}
type canonicalAttemptFinalizeBody struct {
AttemptID string `json:"attempt_id"`
ExpectedVersion int64 `json:"expected_version"`
}
// AssessmentAttemptResult contains only the candidate-visible result data.
type AssessmentAttemptResult struct {
Attempt domain.AssessmentAttemptPublicSnapshot
Outcome domain.AssessmentAttemptOutcome
CategoryDecision *domain.AssessmentCategoryDecisionSnapshot
NotDeterminedReason string
BasicScore *domain.AssessmentBasicScore
Limitations []string
Summary string
DecidedAt time.Time
}
// FinalizeAttempt stores a pinned-policy decision and its idempotent response
// in the same transaction as the attempt transition.
func (service *AttemptService) FinalizeAttempt(
ctx context.Context,
command FinalizeAssessmentAttemptCommand,
) (outbound.AssessmentAttemptCommandResult, error) {
const location = "AttemptService.FinalizeAttempt"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 {
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
}
body, err := json.Marshal(canonicalAttemptFinalizeBody{
AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion,
})
if err != nil || len(body) > maxAttemptCanonicalBodyBytes {
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
}
keyTime, err := assessmentIdempotencyTime(service.clock())
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err)
}
request, err := service.prepareAttemptIdempotency(finalizeAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime)
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
}
var result outbound.AssessmentAttemptCommandResult
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
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
}
repository := unit.AssessmentAttempts()
if !created {
return replayAttemptFinalize(ctx, repository, request, stored, &result)
}
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
return fmt.Errorf("%s - remove expired finalize response: %w", location, err)
}
return service.finalizeNewAttempt(ctx, unit, repository, request.scope, command, &result)
})
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func replayAttemptFinalize(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
request attemptIdempotencyRequest,
stored outbound.IdempotencyRecord,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "assessment.replayAttemptFinalize"
if stored.Fingerprint != request.record.Fingerprint {
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
}
outcome, err := repository.GetFinalizeOutcome(ctx, request.scope)
if err != nil {
return fmt.Errorf("%s - read immutable finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
return nil
}
func (service *AttemptService) finalizeNewAttempt(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.finalizeNewAttempt"
current, err := lockAttemptForFinalize(ctx, unit, repository, command)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 404, result)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.State() != domain.AssessmentAttemptStateCompleted && command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
}
if current.State() == domain.AssessmentAttemptStateCompleted {
return storeCompletedFinalize(ctx, repository, scope, command, current, result)
}
return service.finalizeActiveAttempt(ctx, unit, repository, scope, command, current, result)
}
func lockAttemptForFinalize(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
command FinalizeAssessmentAttemptCommand,
) (domain.AssessmentAttempt, error) {
const location = "AttemptService.lockAttemptForFinalize"
kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err)
}
selected, err := repository.GetForCandidate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read candidate scope before attempt lock: %w", location, err)
}
selectedSnapshot := selected.Snapshot()
if selected.Kind() != kind {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed before lock: %w", location, domain.ErrInvalidAssessmentAttempt)
}
if err := repository.LockScope(ctx, command.ActorID, selectedSnapshot.Specialization); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock candidate and specialization scope: %w", location, err)
}
current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.Kind() != kind || !sameAttemptSpecialization(current.Snapshot().Specialization, selectedSnapshot.Specialization) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return current, nil
}
// sameAttemptSpecialization compares the optional specializations of two reads
// of one attempt; training attempts have none.
func sameAttemptSpecialization(left, right *domain.SpecializationCode) bool {
if left == nil || right == nil {
return left == right
}
return *left == *right
}
func storeCompletedFinalize(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current domain.AssessmentAttempt,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.storeCompletedFinalize"
if _, err := repository.GetResult(ctx, command.ActorID, command.AttemptID); err != nil {
return fmt.Errorf("%s - completed attempt has no immutable result: %w", location, err)
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: current.PublicSnapshot()}
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store completed finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
func (service *AttemptService) finalizeActiveAttempt(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current domain.AssessmentAttempt,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.finalizeActiveAttempt"
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
}
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
policyID := current.Snapshot().Versions.ProductPolicyVersionID
policy, err := unit.Policies().GetByID(ctx, policyID)
if err != nil {
return fmt.Errorf("%s - read pinned product policy: %w", location, err)
}
if current.State() == domain.AssessmentAttemptStateInProgress {
expired, changed, expireErr := current.ExpireIfDue(databaseTime)
if expireErr != nil {
return fmt.Errorf("%s - apply due attempt deadline: %w", location, expireErr)
}
if changed {
if err := repository.SaveTransition(ctx, current, expired); err != nil {
return fmt.Errorf("%s - persist due attempt deadline: %w", location, err)
}
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
}
}
if pendingItemIDs := current.PendingItemIDs(); len(pendingItemIDs) > 0 {
return storeFinalizePendingItems(ctx, repository, scope, pendingItemIDs, result)
}
updated, changed, decision, finalizeErr := current.FinalizeDemo(
command.ExpectedVersion, policy.Policy().Assessment, databaseTime,
)
if finalizeErr != nil {
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptVersionConflict) {
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
}
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptNotActive) {
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
}
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
}
if err := service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result); err != nil {
return err
}
if !changed {
return nil
}
if err := service.signalObserver.scheduleEndedReview(ctx, unit, updated, databaseTime); err != nil {
return fmt.Errorf("%s - schedule review: %w", location, err)
}
return nil
}
func (service *AttemptService) persistFinalizedAttempt(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current, updated domain.AssessmentAttempt,
changed bool,
decision domain.AssessmentAttemptDecision,
policy domain.PolicyVersion,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.persistFinalizedAttempt"
if changed {
if err := repository.SaveTransition(ctx, current, updated); err != nil {
return fmt.Errorf("%s - persist final decision: %w", location, err)
}
summary, limitations := assessmentFinalizedResultPresentation(updated.Kind())
storedResult, err := domain.NewAssessmentAttemptResultSnapshot(updated, decision, summary, limitations)
if err != nil {
return fmt.Errorf("%s - build immutable result snapshot: %w", location, err)
}
categoryPlan, err := service.categoryDecisions.PrepareFinalizedResult(
ctx, repository, updated, storedResult, policy,
)
if err != nil {
return fmt.Errorf("%s - prepare immutable category result: %w", location, err)
}
if err := repository.SaveResultHistoryEntry(ctx, command.ActorID, categoryPlan.Result); err != nil {
return fmt.Errorf("%s - persist immutable result history entry: %w", location, err)
}
if categoryPlan.ReplaceCurrent {
if categoryPlan.CurrentCategory == nil {
return fmt.Errorf("%s - category plan lacks assigned current value: %w", location, domain.ErrInvalidAssessmentCategory)
}
if err := repository.SaveCandidateAssessmentCategory(ctx, *categoryPlan.CurrentCategory); err != nil {
return fmt.Errorf("%s - persist current category: %w", location, err)
}
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store immutable finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
// expressResultSummary is the user-facing text of a finished express run. The
// product UI is in Russian, and the text is stored in the immutable result, so
// a run finished before this text changed keeps the text it was stored with.
const expressResultSummary = "Это тренировочный запуск: он не оценивает и не подтверждает уровень."
// expressEndedSummary is the text of an express run that expired or was left
// unfinished. Like expressResultSummary, it is stored in the immutable result.
const expressEndedSummary = "Тренировочный запуск завершился до окончания: он не оценивает и не подтверждает уровень."
func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) {
if kind == domain.AssessmentAttemptKindDemoExpress {
return expressResultSummary, []string{"demonstration_only"}
}
return "", []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
}
// GetMyResult returns an immutable completed result or a terminal no-result projection.
func (service *AttemptService) GetMyResult(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.GetMyResult"
if userID == uuid.Nil || attemptID.IsZero() {
return AssessmentAttemptResult{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden)
}
var result AssessmentAttemptResult
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
return err
}
var readErr error
result, readErr = service.readAttemptResult(ctx, unit, userID, attemptID)
return readErr
})
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *AttemptService) readAttemptResult(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.readAttemptResult"
attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, err)
}
snapshot := attempt.Snapshot()
if err := validateAttemptResultState(snapshot); err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - validate terminal attempt: %w", location, err)
}
if snapshot.State == domain.AssessmentAttemptStateCompleted {
return readCompletedAttemptResult(ctx, unit, userID, attemptID, attempt)
}
return terminalAttemptResult(attempt)
}
func validateAttemptResultState(snapshot domain.AssessmentAttemptSnapshot) error {
switch snapshot.State {
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
domain.AssessmentAttemptStateInsufficientBank:
if snapshot.EndedAt.IsZero() {
return domain.ErrInvalidAssessmentAttempt
}
return nil
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
return ErrAttemptStateConflict
default:
return domain.ErrInvalidAssessmentAttempt
}
}
func readCompletedAttemptResult(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
attempt domain.AssessmentAttempt,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.readCompletedAttemptResult"
stored, err := unit.AssessmentAttempts().GetResultHistoryEntry(ctx, userID, attemptID)
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err)
}
if !assessmentResultMatchesAttempt(stored.Result, attempt) {
return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt)
}
entry, err := domain.RestoreAssessmentAttemptResultHistoryEntry(stored)
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err)
}
return AssessmentAttemptResultFromHistoryEntry(entry), nil
}
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
snapshot := attempt.Snapshot()
result := AssessmentAttemptResult{Attempt: attempt.PublicSnapshot(), DecidedAt: snapshot.EndedAt}
switch snapshot.Kind {
case domain.AssessmentAttemptKindDemoExpress:
result.Outcome = domain.AssessmentAttemptOutcomeDemonstration
result.Summary = expressEndedSummary
case domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective:
result.Limitations = []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
result.Outcome = domain.AssessmentAttemptOutcomeNotDetermined
if snapshot.State == domain.AssessmentAttemptStateExpired {
result.NotDeterminedReason = "expired"
} else {
result.NotDeterminedReason = "insufficient_bank"
}
default:
return AssessmentAttemptResult{}, fmt.Errorf("AttemptService.terminalAttemptResult - attempt kind is unsupported: %w", domain.ErrInvalidAssessmentAttempt)
}
return result, nil
}
func assessmentResultMatchesAttempt(
result domain.AssessmentAttemptResultSnapshot,
attempt domain.AssessmentAttempt,
) bool {
snapshot := attempt.Snapshot()
pins := result.Pins
public := attempt.PublicSnapshot()
return reflect.DeepEqual(result.Attempt, public) && result.Outcome == snapshot.Outcome &&
result.Attempt.FinishedAt != nil && snapshot.EndedAt.Equal(*result.Attempt.FinishedAt) &&
pins.ProductPolicyVersionID == snapshot.Versions.ProductPolicyVersionID &&
pins.ProductPolicyVersion == snapshot.Versions.ProductPolicyVersion &&
pins.GradingPolicyVersionID == snapshot.Versions.GradingPolicyVersionID &&
pins.OpeningID == snapshot.Versions.OpeningID && pins.OpeningManifestHash == snapshot.Versions.OpeningManifestHash &&
pins.TrainingBindingID == snapshot.Versions.TrainingBindingID &&
pins.TrainingManifestHash == snapshot.Versions.TrainingManifestHash &&
pins.BankVersion == snapshot.Versions.BankVersion && pins.AlgorithmVersion == snapshot.Versions.AlgorithmVersion
}
func assessmentAttemptResultFromSnapshot(
snapshot domain.AssessmentAttemptResultSnapshot,
) AssessmentAttemptResult {
return AssessmentAttemptResult{
Attempt: snapshot.Attempt, Outcome: snapshot.Outcome,
NotDeterminedReason: snapshot.NotDeterminedReason,
BasicScore: snapshot.BasicScore, Limitations: append([]string{}, snapshot.Limitations...),
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
}
}
// AssessmentAttemptResultFromHistoryEntry is the candidate-visible form of one
// stored result, with the category decision captured when it was stored. A
// legacy v1 entry has no decision.
func AssessmentAttemptResultFromHistoryEntry(entry domain.AssessmentAttemptResultHistoryEntry) AssessmentAttemptResult {
result := assessmentAttemptResultFromSnapshot(entry.Result)
if entry.CategoryDecision != nil {
decision := *entry.CategoryDecision
result.CategoryDecision = &decision
}
return result
}