feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,404 @@
|
||||
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
|
||||
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)
|
||||
}
|
||||
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 {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result)
|
||||
}
|
||||
|
||||
func persistFinalizedAttempt(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
current, updated domain.AssessmentAttempt,
|
||||
changed bool,
|
||||
decision domain.AssessmentAttemptDecision,
|
||||
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)
|
||||
}
|
||||
if err := repository.SaveResult(ctx, command.ActorID, storedResult); err != nil {
|
||||
return fmt.Errorf("%s - persist immutable result snapshot: %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
|
||||
}
|
||||
|
||||
func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) {
|
||||
if kind == domain.AssessmentAttemptKindDemoExpress {
|
||||
return "This training run is educational only. It does not assess or confirm a grade.", []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().GetResult(ctx, userID, attemptID)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err)
|
||||
}
|
||||
if !assessmentResultMatchesAttempt(stored, attempt) {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return assessmentAttemptResultFromSnapshot(stored), 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 = "This training run ended before completion. It does not assess or confirm a grade."
|
||||
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,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user