1389 lines
60 KiB
Go
1389 lines
60 KiB
Go
package domain
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"maps"
|
|
"regexp"
|
|
"slices"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var (
|
|
// ErrInvalidAssessmentAttempt reports a malformed attempt or stored
|
|
// snapshot. Error text never includes task text or a submitted answer.
|
|
ErrInvalidAssessmentAttempt = errors.New("invalid assessment attempt")
|
|
// ErrAssessmentAttemptVersionConflict reports a command based on a stale
|
|
// attempt version.
|
|
ErrAssessmentAttemptVersionConflict = errors.New("assessment attempt version changed")
|
|
// ErrAssessmentAttemptNotActive reports a work command against an attempt
|
|
// that cannot accept more work.
|
|
ErrAssessmentAttemptNotActive = errors.New("assessment attempt is not active")
|
|
)
|
|
|
|
const maxAssessmentAttemptItems = 220
|
|
|
|
var assessmentVersionLabelPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
|
|
var assessmentPublicTaskElementIDPattern = regexp.MustCompile(`^job_[1-9][0-9]{0,1}$`)
|
|
|
|
// AssessmentAttemptID identifies one assessment attempt.
|
|
type AssessmentAttemptID uuid.UUID
|
|
|
|
// NewAssessmentAttemptID returns a time-ordered UUIDv7.
|
|
func NewAssessmentAttemptID() (AssessmentAttemptID, error) {
|
|
id, err := uuid.NewV7()
|
|
if err != nil {
|
|
return AssessmentAttemptID{}, fmt.Errorf("domain.NewAssessmentAttemptID - generate ID: %w", err)
|
|
}
|
|
return AssessmentAttemptID(id), nil
|
|
}
|
|
|
|
func (id AssessmentAttemptID) UUID() uuid.UUID { return uuid.UUID(id) }
|
|
func (id AssessmentAttemptID) String() string { return uuid.UUID(id).String() }
|
|
func (id AssessmentAttemptID) IsZero() bool { return uuid.UUID(id) == uuid.Nil }
|
|
|
|
// AssessmentAttemptKind distinguishes a root quota attempt, a corrective
|
|
// attempt in its chain, and a training-only run.
|
|
type AssessmentAttemptKind string
|
|
|
|
const (
|
|
AssessmentAttemptKindRoot AssessmentAttemptKind = "root"
|
|
AssessmentAttemptKindCorrective AssessmentAttemptKind = "corrective"
|
|
AssessmentAttemptKindDemoExpress AssessmentAttemptKind = "demo_express"
|
|
)
|
|
|
|
// AssessmentAttemptMode is selected by the server and pinned to an attempt.
|
|
type AssessmentAttemptMode string
|
|
|
|
const (
|
|
AssessmentAttemptModeDemoBasic AssessmentAttemptMode = "demo_basic"
|
|
AssessmentAttemptModeAdaptive AssessmentAttemptMode = "adaptive"
|
|
AssessmentAttemptModeDemoExpress AssessmentAttemptMode = "demo_express"
|
|
)
|
|
|
|
// AssessmentAttemptState is the persisted lifecycle state of an attempt.
|
|
// The initial attempt flow creates and resumes in-progress attempts; later
|
|
// commands add the remaining transitions.
|
|
type AssessmentAttemptState string
|
|
|
|
const (
|
|
AssessmentAttemptStateInProgress AssessmentAttemptState = "in_progress"
|
|
AssessmentAttemptStatePracticePending AssessmentAttemptState = "practice_pending"
|
|
AssessmentAttemptStateAdditionalPracticePending AssessmentAttemptState = "additional_practice_pending"
|
|
AssessmentAttemptStateReadyToFinalize AssessmentAttemptState = "ready_to_finalize"
|
|
AssessmentAttemptStateCompleted AssessmentAttemptState = "completed"
|
|
AssessmentAttemptStateExpired AssessmentAttemptState = "expired"
|
|
AssessmentAttemptStateInsufficientBank AssessmentAttemptState = "insufficient_bank"
|
|
)
|
|
|
|
// AssessmentAttemptOutcome is the final decision persisted by the scoring
|
|
// command. Only a non-confirming result may continue into a lower-grade chain.
|
|
type AssessmentAttemptOutcome string
|
|
|
|
const (
|
|
AssessmentAttemptOutcomeConfirmed AssessmentAttemptOutcome = "confirmed"
|
|
AssessmentAttemptOutcomeNotConfirmed AssessmentAttemptOutcome = "not_confirmed"
|
|
AssessmentAttemptOutcomeNotDetermined AssessmentAttemptOutcome = "not_determined"
|
|
AssessmentAttemptOutcomeDemonstration AssessmentAttemptOutcome = "demonstration"
|
|
)
|
|
|
|
// AssessmentAttemptVersions pins the product policy, assessment bank and
|
|
// algorithm versions used to build an attempt. GradingPolicyVersionID is the
|
|
// policy referenced by the category opening; the public contract exposes the
|
|
// product policy number as policy_version.
|
|
type AssessmentAttemptVersions struct {
|
|
ProductPolicyVersionID PolicyVersionID
|
|
ProductPolicyVersion int32
|
|
GradingPolicyVersionID PolicyVersionID
|
|
OpeningID uuid.UUID
|
|
OpeningManifestHash [sha256.Size]byte
|
|
TrainingBindingID uuid.UUID
|
|
TrainingManifestHash [sha256.Size]byte
|
|
BankVersion string
|
|
AlgorithmVersion string
|
|
}
|
|
|
|
// AssessmentAttemptItemInput is one generated variant selected for a new
|
|
// attempt. Item order in the slice is the frozen order stored with the
|
|
// attempt.
|
|
type AssessmentAttemptItemInput struct {
|
|
Variant AssessmentVariant
|
|
}
|
|
|
|
// AssessmentAttemptItemSnapshot is the private frozen variant for one item.
|
|
// ReferenceAnswer and answer data must never be serialized to a candidate.
|
|
type AssessmentAttemptItemSnapshot struct {
|
|
ID uuid.UUID
|
|
Ordinal int32
|
|
Variant AssessmentVariant
|
|
Answer json.RawMessage
|
|
AnsweredAt time.Time
|
|
}
|
|
|
|
// assessmentAttemptVariantDocument preserves the original persisted field
|
|
// names while keeping JSON tags off the shared assessment family model.
|
|
type assessmentAttemptVariantDocument struct {
|
|
FamilyID AssessmentFamilyID `json:"FamilyID"`
|
|
FamilyKey AssessmentFamilyKey `json:"FamilyKey"`
|
|
FamilyVersion int32 `json:"FamilyVersion"`
|
|
Seed VariantSeed `json:"Seed"`
|
|
Parameters map[string]int32 `json:"Parameters"`
|
|
Statement string `json:"Statement"`
|
|
ReferenceAnswer string `json:"ReferenceAnswer"`
|
|
AnswerFormat string `json:"AnswerFormat"`
|
|
// Options is present only for a choice variant, so the documents of the
|
|
// other formats keep the layout they were stored with.
|
|
Options []assessmentAttemptChoiceOptionDocument `json:"Options,omitempty"`
|
|
Rubric AssessmentRubric `json:"Rubric"`
|
|
}
|
|
|
|
type assessmentAttemptChoiceOptionDocument struct {
|
|
ID string `json:"ID"`
|
|
Text string `json:"Text"`
|
|
}
|
|
|
|
func assessmentAttemptChoiceOptionDocuments(options []AssessmentChoiceOption) []assessmentAttemptChoiceOptionDocument {
|
|
if len(options) == 0 {
|
|
return nil
|
|
}
|
|
documents := make([]assessmentAttemptChoiceOptionDocument, len(options))
|
|
for index, option := range options {
|
|
documents[index] = assessmentAttemptChoiceOptionDocument(option)
|
|
}
|
|
return documents
|
|
}
|
|
|
|
func assessmentAttemptChoiceOptionsFromDocuments(documents []assessmentAttemptChoiceOptionDocument) []AssessmentChoiceOption {
|
|
if len(documents) == 0 {
|
|
return nil
|
|
}
|
|
options := make([]AssessmentChoiceOption, len(documents))
|
|
for index, document := range documents {
|
|
options[index] = AssessmentChoiceOption(document)
|
|
}
|
|
return options
|
|
}
|
|
|
|
func assessmentAttemptVariantDocumentFromVariant(variant AssessmentVariant) assessmentAttemptVariantDocument {
|
|
var document assessmentAttemptVariantDocument
|
|
document.FamilyID = variant.FamilyID
|
|
document.FamilyKey = variant.FamilyKey
|
|
document.FamilyVersion = variant.FamilyVersion
|
|
document.Seed = variant.Seed
|
|
document.Parameters = variant.Parameters
|
|
document.Statement = variant.Statement
|
|
document.ReferenceAnswer = variant.ReferenceAnswer
|
|
document.AnswerFormat = variant.AnswerFormat
|
|
document.Options = assessmentAttemptChoiceOptionDocuments(variant.Options)
|
|
document.Rubric = variant.Rubric
|
|
return document
|
|
}
|
|
|
|
func (document assessmentAttemptVariantDocument) variant() AssessmentVariant {
|
|
var variant AssessmentVariant
|
|
variant.FamilyID = document.FamilyID
|
|
variant.FamilyKey = document.FamilyKey
|
|
variant.FamilyVersion = document.FamilyVersion
|
|
variant.Seed = document.Seed
|
|
variant.Parameters = document.Parameters
|
|
variant.Statement = document.Statement
|
|
variant.ReferenceAnswer = document.ReferenceAnswer
|
|
variant.AnswerFormat = document.AnswerFormat
|
|
variant.Options = assessmentAttemptChoiceOptionsFromDocuments(document.Options)
|
|
variant.Rubric = document.Rubric
|
|
return variant
|
|
}
|
|
|
|
// MarshalAssessmentAttemptVariant encodes the frozen private variant using
|
|
// its established storage field names.
|
|
func MarshalAssessmentAttemptVariant(variant AssessmentVariant) ([]byte, error) {
|
|
return json.Marshal(assessmentAttemptVariantDocumentFromVariant(variant))
|
|
}
|
|
|
|
// UnmarshalAssessmentAttemptVariant strictly decodes one frozen private
|
|
// variant from storage.
|
|
func UnmarshalAssessmentAttemptVariant(encoded []byte) (AssessmentVariant, error) {
|
|
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
var document assessmentAttemptVariantDocument
|
|
if err := decoder.Decode(&document); err != nil {
|
|
return AssessmentVariant{}, fmt.Errorf("domain.UnmarshalAssessmentAttemptVariant - decode: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
return AssessmentVariant{}, fmt.Errorf("domain.UnmarshalAssessmentAttemptVariant - trailing data: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return document.variant(), nil
|
|
}
|
|
|
|
func (item AssessmentAttemptItemSnapshot) String() string { return redactedAssessmentAttempt }
|
|
func (item AssessmentAttemptItemSnapshot) GoString() string { return redactedAssessmentAttempt }
|
|
func (item AssessmentAttemptItemSnapshot) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedAssessmentAttempt)
|
|
}
|
|
func (item AssessmentAttemptItemSnapshot) LogValue() slog.Value {
|
|
return slog.GroupValue(slog.Int("ordinal", int(item.Ordinal)), slog.String("item_id", item.ID.String()))
|
|
}
|
|
|
|
// AssessmentAttemptSnapshot is the persistence projection. Its items include
|
|
// reference answers and must be treated as secret bank data by adapters.
|
|
type AssessmentAttemptSnapshot struct {
|
|
ID AssessmentAttemptID
|
|
UserID uuid.UUID
|
|
Kind AssessmentAttemptKind
|
|
Mode AssessmentAttemptMode
|
|
State AssessmentAttemptState
|
|
Outcome AssessmentAttemptOutcome
|
|
BankCategory AssessmentCategory
|
|
Specialization *SpecializationCode
|
|
TargetGrade *GradeCode
|
|
TaskLanguage *TaskLanguageCode
|
|
RootAttemptID AssessmentAttemptID
|
|
Versions AssessmentAttemptVersions
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
ExpiresAt time.Time
|
|
ChainDeadline time.Time
|
|
IdleTimeoutSeconds int32
|
|
MaxSessions int32
|
|
SessionsUsed int32
|
|
SessionStartedAt time.Time
|
|
LastActivityAt time.Time
|
|
Version int64
|
|
EndedAt time.Time
|
|
Items []AssessmentAttemptItemSnapshot
|
|
}
|
|
|
|
// AssessmentAttemptPublicItem is the allowlisted candidate projection of one
|
|
// frozen item. It deliberately omits family identity, seed, parameters,
|
|
// rubric, reference answer, and submitted answer.
|
|
type AssessmentAttemptPublicItem struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Sequence int32 `json:"sequence"`
|
|
Prompt string `json:"prompt"`
|
|
Content AssessmentAttemptPublicItemContent `json:"content"`
|
|
}
|
|
|
|
// AssessmentAttemptPublicItemContent is an allowlisted candidate-facing
|
|
// projection of the formats currently produced by the reviewed bank.
|
|
type AssessmentAttemptPublicItemContent struct {
|
|
Format string `json:"format"`
|
|
Unit *string `json:"unit,omitempty"`
|
|
// Elements are the elements of an order item or the options of a choice
|
|
// item, in the order of this instance.
|
|
Elements []AssessmentAttemptPublicOption `json:"elements,omitempty"`
|
|
// Multiple says whether a choice item accepts several options. Generated
|
|
// choice variants have one correct option and accept one selection.
|
|
Multiple bool `json:"multiple,omitempty"`
|
|
}
|
|
|
|
// AssessmentAttemptPublicOption is a generated task element or choice option:
|
|
// an opaque ID and a text, not a family or variant identifier.
|
|
type AssessmentAttemptPublicOption struct {
|
|
ID string `json:"id"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// AssessmentAttemptPublicSnapshot is the typed response snapshot retained for
|
|
// idempotent HTTP replay. It contains no owner ID or private grading material.
|
|
type AssessmentAttemptPublicSnapshot struct {
|
|
ID AssessmentAttemptID `json:"id"`
|
|
Version int64 `json:"version"`
|
|
Kind AssessmentAttemptKind `json:"kind"`
|
|
Mode AssessmentAttemptMode `json:"mode"`
|
|
State AssessmentAttemptState `json:"state"`
|
|
Specialization *SpecializationCode `json:"specialization"`
|
|
TargetGrade *GradeCode `json:"target_grade"`
|
|
TaskLanguage *TaskLanguageCode `json:"task_language"`
|
|
RootAttemptID *AssessmentAttemptID `json:"root_attempt_id,omitempty"`
|
|
ChainDeadline *time.Time `json:"chain_deadline,omitempty"`
|
|
PolicyVersion int32 `json:"policy_version"`
|
|
BankVersion string `json:"bank_version"`
|
|
AlgorithmVersion string `json:"algorithm_version"`
|
|
StartedAt time.Time `json:"started_at"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
FinishedAt *time.Time `json:"finished_at"`
|
|
MaxItems int32 `json:"max_items"`
|
|
AnsweredItems int32 `json:"answered_items"`
|
|
SessionsUsed int32 `json:"sessions_used"`
|
|
MaxSessions int32 `json:"max_sessions"`
|
|
IdleTimeout int32 `json:"idle_timeout_seconds"`
|
|
CurrentItem *AssessmentAttemptPublicItem `json:"current_item"`
|
|
Practices []AssessmentAttemptPublicPractice `json:"practices"`
|
|
// Watermark is set when a response is presented, never when it is stored:
|
|
// the retained idempotent response stays free of it, and every presentation
|
|
// derives the same value from the attempt.
|
|
Watermark *AssessmentAttemptPublicWatermark `json:"watermark,omitempty"`
|
|
}
|
|
|
|
// AssessmentAttemptPublicWatermark is the visible pseudonymous code that the
|
|
// task screen shows next to the time. It reveals nothing about the candidate.
|
|
type AssessmentAttemptPublicWatermark struct {
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
// AssessmentAttemptPublicPractice is the empty, explicit practice projection
|
|
// until attempt creation assigns practice items in a later assessment flow.
|
|
type AssessmentAttemptPublicPractice struct {
|
|
Kind string `json:"kind"`
|
|
}
|
|
|
|
func (snapshot AssessmentAttemptSnapshot) String() string { return redactedAssessmentAttempt }
|
|
func (snapshot AssessmentAttemptSnapshot) GoString() string { return redactedAssessmentAttempt }
|
|
func (snapshot AssessmentAttemptSnapshot) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedAssessmentAttempt)
|
|
}
|
|
func (snapshot AssessmentAttemptSnapshot) LogValue() slog.Value {
|
|
return slog.GroupValue(
|
|
slog.String("attempt_id", snapshot.ID.String()),
|
|
slog.String("kind", string(snapshot.Kind)),
|
|
slog.String("state", string(snapshot.State)),
|
|
slog.Int64("version", snapshot.Version),
|
|
)
|
|
}
|
|
|
|
const redactedAssessmentAttempt = "[redacted assessment attempt]"
|
|
|
|
// AssessmentAttempt is one candidate-owned attempt with frozen item variants
|
|
// and execution limits. It is immutable by value; transitions return a copy.
|
|
type AssessmentAttempt struct {
|
|
snapshot AssessmentAttemptSnapshot
|
|
}
|
|
|
|
// NewAssessmentAttemptInput supplies server-resolved state. The caller must
|
|
// authenticate the candidate, resolve an effective policy and reviewed bank,
|
|
// and validate questionnaire/catalog constraints before constructing it.
|
|
type NewAssessmentAttemptInput struct {
|
|
UserID uuid.UUID
|
|
Kind AssessmentAttemptKind
|
|
BankCategory AssessmentCategory
|
|
Specialization *SpecializationCode
|
|
TargetGrade *GradeCode
|
|
TaskLanguage *TaskLanguageCode
|
|
// Chain is the root followed by each corrective attempt in creation order.
|
|
// It is required only for corrective attempts and must come from one
|
|
// transactionally consistent repository read.
|
|
Chain []AssessmentAttempt
|
|
Versions AssessmentAttemptVersions
|
|
Policy PolicyVersion
|
|
CreatedAt time.Time
|
|
Items []AssessmentAttemptItemInput
|
|
}
|
|
|
|
// NewAssessmentAttempt constructs a root, corrective or express attempt and
|
|
// freezes the versions, session limits, and generated item variants. A policy
|
|
// without explicit attempt settings is deliberately unavailable for starts.
|
|
func NewAssessmentAttempt(input NewAssessmentAttemptInput) (AssessmentAttempt, error) {
|
|
const location = "domain.NewAssessmentAttempt"
|
|
if err := validateNewAssessmentAttemptInput(input); err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - validate input: %w", location, err)
|
|
}
|
|
policy := input.Policy.Policy().Assessment
|
|
settings := AssessmentAttemptPolicy{}
|
|
if policy.Attempt != nil {
|
|
settings = *policy.Attempt
|
|
}
|
|
sessions, idleTimeout := settings.MaxSessions, settings.IdleTimeoutSeconds
|
|
if input.Kind == AssessmentAttemptKindDemoExpress {
|
|
sessions, idleTimeout = policy.Training.MaxSessions, policy.Training.IdleTimeoutSeconds
|
|
}
|
|
items, err := buildAssessmentAttemptItems(input.Items)
|
|
if err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - freeze items: %w", location, err)
|
|
}
|
|
id, err := NewAssessmentAttemptID()
|
|
if err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - assign ID: %w", location, err)
|
|
}
|
|
createdAt := canonicalAssessmentTime(input.CreatedAt)
|
|
snapshot := AssessmentAttemptSnapshot{
|
|
ID: id,
|
|
UserID: input.UserID,
|
|
BankCategory: input.BankCategory,
|
|
State: AssessmentAttemptStateInProgress,
|
|
CreatedAt: createdAt,
|
|
UpdatedAt: createdAt,
|
|
IdleTimeoutSeconds: idleTimeout,
|
|
MaxSessions: sessions,
|
|
SessionsUsed: 1,
|
|
SessionStartedAt: createdAt,
|
|
LastActivityAt: createdAt,
|
|
Version: 1,
|
|
Versions: input.Versions,
|
|
Items: items,
|
|
}
|
|
if err := populateAssessmentAttemptTrack(&snapshot, input, settings, createdAt); err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - validate attempt track: %w", location, err)
|
|
}
|
|
return RestoreAssessmentAttempt(snapshot)
|
|
}
|
|
|
|
func validateNewAssessmentAttemptInput(input NewAssessmentAttemptInput) error {
|
|
const location = "domain.validateNewAssessmentAttemptInput"
|
|
if input.UserID == uuid.Nil || input.CreatedAt.IsZero() {
|
|
return fmt.Errorf("%s - user ID and creation time must be set: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if _, err := ParseAssessmentCategory(string(input.BankCategory)); err != nil {
|
|
return fmt.Errorf("%s - bank category is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if !validProductPolicyVersion(input.Policy, input.Versions) {
|
|
return fmt.Errorf("%s - product policy version must match the pinned policy: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if !validAttemptVersionLabels(input.Versions) {
|
|
return fmt.Errorf("%s - bank and algorithm versions must be pinned: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
assessmentPolicy := input.Policy.Policy().Assessment
|
|
switch input.Kind {
|
|
case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective:
|
|
if assessmentPolicy.Attempt == nil {
|
|
return fmt.Errorf("%s - policy has no explicit real attempt settings: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
case AssessmentAttemptKindDemoExpress:
|
|
if assessmentPolicy.Training == nil {
|
|
return fmt.Errorf("%s - policy has no explicit training settings: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if len(input.Items) != int(assessmentPolicy.Training.DemoExpressItemCount) {
|
|
return fmt.Errorf("%s - express item count does not match the pinned training policy: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
default:
|
|
return fmt.Errorf("%s - attempt kind is unknown: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if !validVersionPins(input.Kind, input.Versions) {
|
|
return fmt.Errorf("%s - version pins do not match the attempt kind: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if len(input.Items) == 0 || len(input.Items) > maxAssessmentAttemptItems {
|
|
return fmt.Errorf("%s - attempt must contain 1 to %d frozen items: %w", location, maxAssessmentAttemptItems, ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validProductPolicyVersion(policy PolicyVersion, versions AssessmentAttemptVersions) bool {
|
|
return !policy.IsZero() && policy.Key() == ProductPolicyKey && !versions.ProductPolicyVersionID.IsZero() &&
|
|
versions.ProductPolicyVersionID == policy.ID() && versions.ProductPolicyVersion == policy.Version()
|
|
}
|
|
|
|
func validAttemptVersionLabels(versions AssessmentAttemptVersions) bool {
|
|
return assessmentVersionLabelPattern.MatchString(versions.BankVersion) &&
|
|
assessmentVersionLabelPattern.MatchString(versions.AlgorithmVersion)
|
|
}
|
|
|
|
func validVersionPins(kind AssessmentAttemptKind, versions AssessmentAttemptVersions) bool {
|
|
switch kind {
|
|
case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective:
|
|
return !versions.GradingPolicyVersionID.IsZero() && versions.OpeningID != uuid.Nil &&
|
|
!emptyAssessmentDigest(versions.OpeningManifestHash) && versions.TrainingBindingID == uuid.Nil &&
|
|
emptyAssessmentDigest(versions.TrainingManifestHash)
|
|
case AssessmentAttemptKindDemoExpress:
|
|
return versions.GradingPolicyVersionID.IsZero() && versions.OpeningID == uuid.Nil &&
|
|
emptyAssessmentDigest(versions.OpeningManifestHash) && versions.TrainingBindingID != uuid.Nil &&
|
|
!emptyAssessmentDigest(versions.TrainingManifestHash)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func emptyAssessmentDigest(digest [sha256.Size]byte) bool { return digest == [sha256.Size]byte{} }
|
|
|
|
func populateAssessmentAttemptTrack(
|
|
snapshot *AssessmentAttemptSnapshot,
|
|
input NewAssessmentAttemptInput,
|
|
settings AssessmentAttemptPolicy,
|
|
createdAt time.Time,
|
|
) error {
|
|
snapshot.Kind = input.Kind
|
|
snapshot.Specialization = clonePointer(input.Specialization)
|
|
snapshot.TargetGrade = clonePointer(input.TargetGrade)
|
|
snapshot.TaskLanguage = clonePointer(input.TaskLanguage)
|
|
switch input.Kind {
|
|
case AssessmentAttemptKindRoot:
|
|
return populateRootAttemptTrack(snapshot, input, settings, createdAt)
|
|
case AssessmentAttemptKindCorrective:
|
|
return populateCorrectiveAttemptTrack(snapshot, input, settings, createdAt)
|
|
case AssessmentAttemptKindDemoExpress:
|
|
return populateExpressAttemptTrack(snapshot, input, createdAt)
|
|
default:
|
|
return fmt.Errorf("domain.populateAssessmentAttemptTrack - attempt kind is unknown: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
}
|
|
|
|
func populateRootAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, settings AssessmentAttemptPolicy, createdAt time.Time) error {
|
|
const location = "domain.populateRootAttemptTrack"
|
|
if len(input.Chain) != 0 || !validRealAssessmentTrack(input.Specialization, input.TargetGrade) || !validTaskLanguage(input.TaskLanguage) {
|
|
return fmt.Errorf("%s - root attempt requires specialization and grade and has no parent: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
snapshot.Mode = realModeFromPolicy(settings.RealMode)
|
|
snapshot.RootAttemptID = snapshot.ID
|
|
snapshot.ChainDeadline = createdAt.Add(settings.ChainDeadline.Duration())
|
|
snapshot.ExpiresAt = minTime(createdAt.Add(settings.Lifetime.Duration()), snapshot.ChainDeadline)
|
|
return nil
|
|
}
|
|
|
|
func populateCorrectiveAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, settings AssessmentAttemptPolicy, createdAt time.Time) error {
|
|
const location = "domain.populateCorrectiveAttemptTrack"
|
|
if len(input.Chain) == 0 || !validRealAssessmentTrack(input.Specialization, input.TargetGrade) || !validTaskLanguage(input.TaskLanguage) {
|
|
return fmt.Errorf("%s - corrective attempt requires a root, specialization, and grade: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
chain := make([]AssessmentAttemptSnapshot, len(input.Chain))
|
|
for index, attempt := range input.Chain {
|
|
chain[index] = attempt.snapshot
|
|
}
|
|
if !rootCanContinue(input.UserID, input.Specialization, input.TargetGrade, chain, createdAt) {
|
|
return fmt.Errorf("%s - corrective attempt does not continue an eligible failed or expired chain for this candidate: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
snapshot.Mode = realModeFromPolicy(settings.RealMode)
|
|
root := chain[0]
|
|
snapshot.RootAttemptID = root.ID
|
|
snapshot.ChainDeadline = root.ChainDeadline
|
|
snapshot.ExpiresAt = minTime(createdAt.Add(settings.Lifetime.Duration()), root.ChainDeadline)
|
|
return nil
|
|
}
|
|
|
|
func rootCanContinue(
|
|
userID uuid.UUID,
|
|
specialization *SpecializationCode,
|
|
grade *GradeCode,
|
|
chain []AssessmentAttemptSnapshot,
|
|
createdAt time.Time,
|
|
) bool {
|
|
if len(chain) == 0 {
|
|
return false
|
|
}
|
|
root := chain[0]
|
|
if !validCorrectionRoot(root, userID, specialization, createdAt) {
|
|
return false
|
|
}
|
|
previous := root
|
|
for index := 1; index < len(chain); index++ {
|
|
current := chain[index]
|
|
if !validCorrectionPredecessor(root, previous, current, userID, specialization) {
|
|
return false
|
|
}
|
|
previous = current
|
|
}
|
|
return lowerGradeFollows(grade, previous.TargetGrade) && !createdAt.Before(previous.UpdatedAt)
|
|
}
|
|
|
|
func validCorrectionRoot(
|
|
root AssessmentAttemptSnapshot,
|
|
userID uuid.UUID,
|
|
specialization *SpecializationCode,
|
|
createdAt time.Time,
|
|
) bool {
|
|
return root.Kind == AssessmentAttemptKindRoot && root.RootAttemptID == root.ID && root.UserID == userID &&
|
|
root.Specialization != nil && *root.Specialization == *specialization && validTerminalForCorrection(root) &&
|
|
!createdAt.IsZero() && createdAt.Before(root.ChainDeadline)
|
|
}
|
|
|
|
func validCorrectionPredecessor(
|
|
root AssessmentAttemptSnapshot,
|
|
previous AssessmentAttemptSnapshot,
|
|
current AssessmentAttemptSnapshot,
|
|
userID uuid.UUID,
|
|
specialization *SpecializationCode,
|
|
) bool {
|
|
return current.Kind == AssessmentAttemptKindCorrective && current.RootAttemptID == root.ID &&
|
|
current.UserID == userID && current.Specialization != nil && *current.Specialization == *specialization &&
|
|
current.ChainDeadline.Equal(root.ChainDeadline) && validTerminalForCorrection(current) &&
|
|
lowerGradeFollows(current.TargetGrade, previous.TargetGrade) && !current.CreatedAt.Before(previous.UpdatedAt)
|
|
}
|
|
|
|
func lowerGradeFollows(lowerGrade, higherGrade *GradeCode) bool {
|
|
return lowerGrade != nil && higherGrade != nil && isLowerGrade(*lowerGrade, *higherGrade)
|
|
}
|
|
|
|
func validTerminalForCorrection(attempt AssessmentAttemptSnapshot) bool {
|
|
switch attempt.State {
|
|
case AssessmentAttemptStateExpired:
|
|
return attempt.Outcome == ""
|
|
case AssessmentAttemptStateCompleted:
|
|
return attempt.Outcome == AssessmentAttemptOutcomeNotConfirmed ||
|
|
attempt.Outcome == AssessmentAttemptOutcomeNotDetermined
|
|
case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending,
|
|
AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize,
|
|
AssessmentAttemptStateInsufficientBank:
|
|
return false
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func populateExpressAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, createdAt time.Time) error {
|
|
const location = "domain.populateExpressAttemptTrack"
|
|
if len(input.Chain) != 0 || input.Specialization != nil || input.TargetGrade != nil || input.TaskLanguage != nil {
|
|
return fmt.Errorf("%s - express attempt has no category, grade, language, or parent: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
training := input.Policy.Policy().Assessment.Training
|
|
if training == nil {
|
|
return fmt.Errorf("%s - express attempt requires separate training settings: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
snapshot.Mode = AssessmentAttemptModeDemoExpress
|
|
snapshot.ExpiresAt = createdAt.Add(time.Duration(training.DemoExpressDurationSeconds) * time.Second)
|
|
return nil
|
|
}
|
|
|
|
func validRealAssessmentTrack(specialization *SpecializationCode, grade *GradeCode) bool {
|
|
return specialization != nil && specialization.IsKnown() && grade != nil && grade.IsKnown()
|
|
}
|
|
|
|
func validTaskLanguage(language *TaskLanguageCode) bool {
|
|
return language == nil || language.IsKnown()
|
|
}
|
|
|
|
func realModeFromPolicy(mode AssessmentRealMode) AssessmentAttemptMode {
|
|
return AssessmentAttemptMode(mode)
|
|
}
|
|
|
|
func isLowerGrade(candidate, current GradeCode) bool {
|
|
gradeOrder := map[GradeCode]int{GradeIntern: 0, GradeJunior: 1, GradeMiddle: 2, GradeSenior: 3}
|
|
candidateRank, candidateOK := gradeOrder[candidate]
|
|
currentRank, currentOK := gradeOrder[current]
|
|
return candidateOK && currentOK && candidateRank < currentRank
|
|
}
|
|
|
|
func minTime(left, right time.Time) time.Time {
|
|
if left.Before(right) {
|
|
return left
|
|
}
|
|
return right
|
|
}
|
|
|
|
func buildAssessmentAttemptItems(input []AssessmentAttemptItemInput) ([]AssessmentAttemptItemSnapshot, error) {
|
|
const location = "domain.buildAssessmentAttemptItems"
|
|
items := make([]AssessmentAttemptItemSnapshot, 0, len(input))
|
|
seenIDs := make(map[uuid.UUID]struct{}, len(input))
|
|
seenFamilies := make(map[AssessmentFamilyKey]struct{}, len(input))
|
|
for index, itemInput := range input {
|
|
variant := cloneAssessmentVariant(itemInput.Variant)
|
|
if !validFrozenVariant(variant) {
|
|
return nil, fmt.Errorf("%s - item %d has invalid generated content: %w", location, index+1, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if _, exists := seenFamilies[variant.FamilyKey]; exists {
|
|
return nil, fmt.Errorf("%s - item families must be unique: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
seenFamilies[variant.FamilyKey] = struct{}{}
|
|
id, err := uuid.NewV7()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - assign item ID: %w", location, err)
|
|
}
|
|
if _, exists := seenIDs[id]; exists {
|
|
return nil, fmt.Errorf("%s - generated item ID was repeated: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
seenIDs[id] = struct{}{}
|
|
items = append(items, AssessmentAttemptItemSnapshot{ID: id, Ordinal: int32(index + 1), Variant: variant})
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
func validFrozenVariant(variant AssessmentVariant) bool {
|
|
if variant.FamilyID.IsZero() || variant.FamilyVersion < 1 || !validFrozenVariantFormat(variant) ||
|
|
variant.ReferenceAnswer == "" || !utf8.ValidString(variant.ReferenceAnswer) ||
|
|
!utf8.ValidString(variant.Statement) || len(variant.Statement) == 0 || len(variant.Statement) > maxStatementBytes ||
|
|
!validStoredFamilyKey(variant.FamilyKey) || !validStoredVariantRubric(variant.Rubric) {
|
|
return false
|
|
}
|
|
encoded, err := MarshalAssessmentAttemptVariant(variant)
|
|
return err == nil && len(encoded) <= maxAssessmentAttemptVariantBytes
|
|
}
|
|
|
|
// validFrozenVariantFormat accepts the answer formats that the bank
|
|
// produces. Only a choice variant carries options, and its key must name one
|
|
// of them.
|
|
func validFrozenVariantFormat(variant AssessmentVariant) bool {
|
|
switch variant.AnswerFormat {
|
|
case AnswerFormatInteger, AnswerFormatIntegerSequence:
|
|
return len(variant.Options) == 0
|
|
case AnswerFormatChoice:
|
|
return validFrozenChoiceVariant(variant)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
const maxAssessmentAttemptVariantBytes = 1 << 20
|
|
|
|
func validStoredFamilyKey(value AssessmentFamilyKey) bool {
|
|
parsed, err := ParseAssessmentFamilyKey(string(value))
|
|
return err == nil && parsed == value
|
|
}
|
|
|
|
func validStoredVariantRubric(rubric AssessmentRubric) bool {
|
|
if !utf8.ValidString(rubric.Principle) ||
|
|
len(rubric.Principle) == 0 || len(rubric.Principle) > maxAssessmentTextLength ||
|
|
len(rubric.Criteria) == 0 || len(rubric.Criteria) > maxAssessmentRubricCriteria ||
|
|
rubric.validate("domain.validStoredVariantRubric") != nil {
|
|
return false
|
|
}
|
|
for _, criterion := range rubric.Criteria {
|
|
if !assessmentCriterionIDPattern.MatchString(criterion.ID) || !utf8.ValidString(criterion.Description) ||
|
|
len(criterion.Description) == 0 || len(criterion.Description) > maxAssessmentTextLength {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func cloneAssessmentVariant(variant AssessmentVariant) AssessmentVariant {
|
|
variant.Parameters = maps.Clone(variant.Parameters)
|
|
variant.Options = cloneChoiceOptions(variant.Options)
|
|
variant.Rubric = variant.Rubric.clone()
|
|
return variant
|
|
}
|
|
|
|
// RestoreAssessmentAttempt validates and clones a stored attempt snapshot.
|
|
func RestoreAssessmentAttempt(snapshot AssessmentAttemptSnapshot) (AssessmentAttempt, error) {
|
|
const location = "domain.RestoreAssessmentAttempt"
|
|
canonicalizeAssessmentAttemptTimes(&snapshot)
|
|
if err := validateAssessmentAttemptSnapshot(snapshot); err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - validate snapshot: %w", location, err)
|
|
}
|
|
answerThrough := snapshot.UpdatedAt
|
|
if !snapshot.EndedAt.IsZero() {
|
|
answerThrough = minTime(answerThrough, snapshot.EndedAt)
|
|
}
|
|
items, err := cloneAndValidateAssessmentAttemptItems(
|
|
snapshot.Items, snapshot.CreatedAt, answerThrough, snapshot.ExpiresAt,
|
|
)
|
|
if err != nil {
|
|
return AssessmentAttempt{}, fmt.Errorf("%s - validate items: %w", location, err)
|
|
}
|
|
snapshot.Specialization = clonePointer(snapshot.Specialization)
|
|
snapshot.TargetGrade = clonePointer(snapshot.TargetGrade)
|
|
snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage)
|
|
snapshot.Items = items
|
|
return AssessmentAttempt{snapshot: snapshot}, nil
|
|
}
|
|
|
|
func canonicalizeAssessmentAttemptTimes(snapshot *AssessmentAttemptSnapshot) {
|
|
snapshot.CreatedAt = canonicalAssessmentTime(snapshot.CreatedAt)
|
|
snapshot.UpdatedAt = canonicalAssessmentTime(snapshot.UpdatedAt)
|
|
snapshot.ExpiresAt = canonicalAssessmentTime(snapshot.ExpiresAt)
|
|
snapshot.ChainDeadline = canonicalAssessmentTime(snapshot.ChainDeadline)
|
|
snapshot.SessionStartedAt = canonicalAssessmentTime(snapshot.SessionStartedAt)
|
|
snapshot.LastActivityAt = canonicalAssessmentTime(snapshot.LastActivityAt)
|
|
snapshot.EndedAt = canonicalAssessmentTime(snapshot.EndedAt)
|
|
for index := range snapshot.Items {
|
|
snapshot.Items[index].AnsweredAt = canonicalAssessmentTime(snapshot.Items[index].AnsweredAt)
|
|
}
|
|
}
|
|
|
|
func canonicalAssessmentTime(value time.Time) time.Time {
|
|
if value.IsZero() {
|
|
return time.Time{}
|
|
}
|
|
return time.UnixMicro(value.UTC().UnixMicro()).UTC()
|
|
}
|
|
|
|
func validateAssessmentAttemptSnapshot(snapshot AssessmentAttemptSnapshot) error {
|
|
const location = "domain.validateAssessmentAttemptSnapshot"
|
|
if err := validateAttemptSnapshotIdentity(snapshot); err != nil {
|
|
return fmt.Errorf("%s - identity: %w", location, err)
|
|
}
|
|
if err := validateAttemptSnapshotTimes(snapshot); err != nil {
|
|
return fmt.Errorf("%s - timestamps: %w", location, err)
|
|
}
|
|
if err := validateAttemptSnapshotSessions(snapshot); err != nil {
|
|
return fmt.Errorf("%s - session limits: %w", location, err)
|
|
}
|
|
if err := validateAttemptSnapshotVersions(snapshot.Versions); err != nil {
|
|
return fmt.Errorf("%s - versions: %w", location, err)
|
|
}
|
|
if err := validateAssessmentAttemptTrack(snapshot); err != nil {
|
|
return fmt.Errorf("%s - track: %w", location, err)
|
|
}
|
|
if err := validateAttemptSnapshotState(snapshot); err != nil {
|
|
return fmt.Errorf("%s - state: %w", location, err)
|
|
}
|
|
if len(snapshot.Items) == 0 || len(snapshot.Items) > maxAssessmentAttemptItems {
|
|
return fmt.Errorf("%s - item count is outside the supported range: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAttemptSnapshotIdentity(snapshot AssessmentAttemptSnapshot) error {
|
|
if snapshot.ID.IsZero() || snapshot.UserID == uuid.Nil || snapshot.Version < 1 {
|
|
return fmt.Errorf("attempt ID, user ID, and version must be set: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAttemptSnapshotTimes(snapshot AssessmentAttemptSnapshot) error {
|
|
if snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt) ||
|
|
snapshot.SessionStartedAt.Before(snapshot.CreatedAt) || snapshot.LastActivityAt.Before(snapshot.SessionStartedAt) ||
|
|
snapshot.UpdatedAt.Before(snapshot.LastActivityAt) {
|
|
return fmt.Errorf("created, updated, session, and activity times are inconsistent: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAttemptSnapshotSessions(snapshot AssessmentAttemptSnapshot) error {
|
|
if snapshot.IdleTimeoutSeconds < 60 || snapshot.IdleTimeoutSeconds > maxAssessmentIdleTimeoutSeconds ||
|
|
snapshot.MaxSessions < 1 || snapshot.MaxSessions > maxAssessmentSessions ||
|
|
snapshot.SessionsUsed < 1 || snapshot.SessionsUsed > snapshot.MaxSessions {
|
|
return fmt.Errorf("session limits are outside supported bounds: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAttemptSnapshotVersions(versions AssessmentAttemptVersions) error {
|
|
if !validAttemptVersionLabels(versions) || versions.ProductPolicyVersionID.IsZero() || versions.ProductPolicyVersion < 1 {
|
|
return fmt.Errorf("policy, bank, or algorithm version is invalid: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAttemptSnapshotState(snapshot AssessmentAttemptSnapshot) error {
|
|
switch snapshot.State {
|
|
case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending,
|
|
AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize:
|
|
if !snapshot.EndedAt.IsZero() || snapshot.Outcome != "" {
|
|
return fmt.Errorf("an active attempt has no end time or outcome: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
if snapshot.State == AssessmentAttemptStateReadyToFinalize && !allAssessmentAttemptItemsAnswered(snapshot.Items) {
|
|
return fmt.Errorf("an attempt is ready to finalize only after all required items are answered: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
case AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank:
|
|
if !validAttemptEndTime(snapshot) || snapshot.Outcome != "" {
|
|
return fmt.Errorf("an expired attempt has an end time: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
case AssessmentAttemptStateCompleted:
|
|
if !validAttemptEndTime(snapshot) || !validAssessmentAttemptOutcome(snapshot.Outcome) ||
|
|
!validAssessmentAttemptOutcomeForKind(snapshot.Kind, snapshot.Outcome) {
|
|
return fmt.Errorf("a completed attempt has a valid outcome and end time: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
default:
|
|
return fmt.Errorf("attempt state is unknown: %w", ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validAssessmentAttemptOutcomeForKind(kind AssessmentAttemptKind, outcome AssessmentAttemptOutcome) bool {
|
|
if kind == AssessmentAttemptKindDemoExpress {
|
|
return outcome == AssessmentAttemptOutcomeDemonstration
|
|
}
|
|
return outcome != AssessmentAttemptOutcomeDemonstration
|
|
}
|
|
|
|
func validAttemptEndTime(snapshot AssessmentAttemptSnapshot) bool {
|
|
return !snapshot.EndedAt.IsZero() && !snapshot.EndedAt.Before(snapshot.CreatedAt) &&
|
|
!snapshot.EndedAt.Before(snapshot.LastActivityAt) && !snapshot.UpdatedAt.Before(snapshot.EndedAt)
|
|
}
|
|
|
|
func validAssessmentAttemptOutcome(outcome AssessmentAttemptOutcome) bool {
|
|
switch outcome {
|
|
case AssessmentAttemptOutcomeConfirmed, AssessmentAttemptOutcomeNotConfirmed, AssessmentAttemptOutcomeNotDetermined,
|
|
AssessmentAttemptOutcomeDemonstration:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validateAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) error {
|
|
const location = "domain.validateAssessmentAttemptTrack"
|
|
switch snapshot.Kind {
|
|
case AssessmentAttemptKindRoot:
|
|
if !validRootAssessmentAttemptTrack(snapshot) {
|
|
return fmt.Errorf("%s - root track is inconsistent: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
case AssessmentAttemptKindCorrective:
|
|
if !validCorrectiveAssessmentAttemptTrack(snapshot) {
|
|
return fmt.Errorf("%s - corrective track is inconsistent: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
case AssessmentAttemptKindDemoExpress:
|
|
if !validExpressAssessmentAttemptTrack(snapshot) {
|
|
return fmt.Errorf("%s - express track is inconsistent: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
default:
|
|
return fmt.Errorf("%s - attempt kind is unknown: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validRootAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool {
|
|
return validAssessmentCategory(snapshot.BankCategory) && validRealAssessmentTrack(snapshot.Specialization, snapshot.TargetGrade) && validTaskLanguage(snapshot.TaskLanguage) &&
|
|
snapshot.RootAttemptID == snapshot.ID && validChainDeadlines(snapshot) && validRealAttemptMode(snapshot.Mode) &&
|
|
validVersionPins(snapshot.Kind, snapshot.Versions)
|
|
}
|
|
|
|
func validCorrectiveAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool {
|
|
return validAssessmentCategory(snapshot.BankCategory) && validRealAssessmentTrack(snapshot.Specialization, snapshot.TargetGrade) && validTaskLanguage(snapshot.TaskLanguage) &&
|
|
!snapshot.RootAttemptID.IsZero() && snapshot.RootAttemptID != snapshot.ID && validChainDeadlines(snapshot) &&
|
|
validRealAttemptMode(snapshot.Mode) && validVersionPins(snapshot.Kind, snapshot.Versions)
|
|
}
|
|
|
|
func validExpressAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool {
|
|
return validAssessmentCategory(snapshot.BankCategory) && snapshot.Specialization == nil && snapshot.TargetGrade == nil && snapshot.TaskLanguage == nil &&
|
|
snapshot.RootAttemptID.IsZero() && snapshot.ChainDeadline.IsZero() && validAttemptExpiry(snapshot) &&
|
|
snapshot.Mode == AssessmentAttemptModeDemoExpress && validVersionPins(snapshot.Kind, snapshot.Versions)
|
|
}
|
|
|
|
func validAssessmentCategory(category AssessmentCategory) bool {
|
|
parsed, err := ParseAssessmentCategory(string(category))
|
|
return err == nil && parsed == category
|
|
}
|
|
|
|
func validChainDeadlines(snapshot AssessmentAttemptSnapshot) bool {
|
|
return !snapshot.ChainDeadline.IsZero() && snapshot.ChainDeadline.After(snapshot.CreatedAt) &&
|
|
validAttemptExpiry(snapshot) && !snapshot.ExpiresAt.After(snapshot.ChainDeadline)
|
|
}
|
|
|
|
func validAttemptExpiry(snapshot AssessmentAttemptSnapshot) bool {
|
|
return !snapshot.ExpiresAt.IsZero() && snapshot.ExpiresAt.After(snapshot.CreatedAt)
|
|
}
|
|
|
|
func validRealAttemptMode(mode AssessmentAttemptMode) bool {
|
|
return mode == AssessmentAttemptModeDemoBasic || mode == AssessmentAttemptModeAdaptive
|
|
}
|
|
|
|
func cloneAndValidateAssessmentAttemptItems(
|
|
items []AssessmentAttemptItemSnapshot,
|
|
createdAt time.Time,
|
|
updatedAt time.Time,
|
|
expiresAt time.Time,
|
|
) ([]AssessmentAttemptItemSnapshot, error) {
|
|
const location = "domain.cloneAndValidateAssessmentAttemptItems"
|
|
result := make([]AssessmentAttemptItemSnapshot, 0, len(items))
|
|
seenIDs := make(map[uuid.UUID]struct{}, len(items))
|
|
seenFamilies := make(map[AssessmentFamilyKey]struct{}, len(items))
|
|
for index, item := range items {
|
|
if !validAssessmentAttemptItem(item, index, createdAt, updatedAt, expiresAt) {
|
|
return nil, fmt.Errorf("%s - item order, identity, or generated content is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if _, exists := seenIDs[item.ID]; exists {
|
|
return nil, fmt.Errorf("%s - item IDs must be unique: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if _, exists := seenFamilies[item.Variant.FamilyKey]; exists {
|
|
return nil, fmt.Errorf("%s - family keys must be unique: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
seenIDs[item.ID] = struct{}{}
|
|
seenFamilies[item.Variant.FamilyKey] = struct{}{}
|
|
item.Variant = cloneAssessmentVariant(item.Variant)
|
|
item.Answer = bytes.Clone(item.Answer)
|
|
result = append(result, item)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func validAssessmentAttemptItem(
|
|
item AssessmentAttemptItemSnapshot,
|
|
index int,
|
|
createdAt time.Time,
|
|
updatedAt time.Time,
|
|
expiresAt time.Time,
|
|
) bool {
|
|
if item.ID == uuid.Nil || item.Ordinal < 1 || int(item.Ordinal) != index+1 || !validFrozenVariant(item.Variant) {
|
|
return false
|
|
}
|
|
if len(item.Answer) == 0 {
|
|
return item.AnsweredAt.IsZero()
|
|
}
|
|
canonical, err := CanonicalAssessmentAttemptAnswer(item.Answer)
|
|
return err == nil && bytes.Equal(canonical, item.Answer) &&
|
|
!item.AnsweredAt.IsZero() && !item.AnsweredAt.Before(createdAt) &&
|
|
!item.AnsweredAt.After(updatedAt) && item.AnsweredAt.Before(expiresAt)
|
|
}
|
|
|
|
// JSON escaping may use up to six bytes per allowed source-code character.
|
|
// Keep headroom for a 65,536-character answer plus its JSON envelope.
|
|
const maxAssessmentAttemptAnswerBytes = 512 << 10
|
|
|
|
// CanonicalAssessmentAttemptAnswer validates one answer JSON object and
|
|
// returns bounded canonical UTF-8 JSON bytes for bytea storage. PostgreSQL
|
|
// jsonb rejects valid strings that decode to U+0000, so answer bytes are not
|
|
// stored as jsonb.
|
|
func CanonicalAssessmentAttemptAnswer(answer json.RawMessage) (json.RawMessage, error) {
|
|
const location = "domain.CanonicalAssessmentAttemptAnswer"
|
|
if len(answer) == 0 || len(answer) > maxAssessmentAttemptAnswerBytes || !utf8.Valid(answer) || !json.Valid(answer) {
|
|
return nil, fmt.Errorf("%s - answer must be bounded valid JSON: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
|
|
decoder := json.NewDecoder(bytes.NewReader(answer))
|
|
decoder.UseNumber()
|
|
var object map[string]any
|
|
if err := decoder.Decode(&object); err != nil || object == nil {
|
|
return nil, fmt.Errorf("%s - answer must be a JSON object: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
return nil, fmt.Errorf("%s - answer contains trailing JSON data: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
format, ok := object["format"].(string)
|
|
if !ok || format == "" {
|
|
return nil, fmt.Errorf("%s - answer format is missing: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
|
|
canonical, err := json.Marshal(object)
|
|
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
|
|
return nil, fmt.Errorf("%s - canonical answer exceeds its storage bound: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
return json.RawMessage(canonical), nil
|
|
}
|
|
|
|
func (attempt AssessmentAttempt) IsZero() bool { return attempt.snapshot.ID.IsZero() }
|
|
func (attempt AssessmentAttempt) IsActive() bool {
|
|
return isAssessmentAttemptActive(attempt.snapshot.State)
|
|
}
|
|
func (attempt AssessmentAttempt) ID() AssessmentAttemptID { return attempt.snapshot.ID }
|
|
func (attempt AssessmentAttempt) UserID() uuid.UUID { return attempt.snapshot.UserID }
|
|
func (attempt AssessmentAttempt) Kind() AssessmentAttemptKind { return attempt.snapshot.Kind }
|
|
func (attempt AssessmentAttempt) Mode() AssessmentAttemptMode { return attempt.snapshot.Mode }
|
|
func (attempt AssessmentAttempt) State() AssessmentAttemptState { return attempt.snapshot.State }
|
|
func (attempt AssessmentAttempt) BankCategory() AssessmentCategory {
|
|
return attempt.snapshot.BankCategory
|
|
}
|
|
func (attempt AssessmentAttempt) Version() int64 { return attempt.snapshot.Version }
|
|
func (attempt AssessmentAttempt) ExpiresAt() time.Time { return attempt.snapshot.ExpiresAt }
|
|
func (attempt AssessmentAttempt) ChainDeadline() time.Time { return attempt.snapshot.ChainDeadline }
|
|
func (attempt AssessmentAttempt) RootAttemptID() AssessmentAttemptID {
|
|
return attempt.snapshot.RootAttemptID
|
|
}
|
|
func (attempt AssessmentAttempt) SessionsUsed() int32 { return attempt.snapshot.SessionsUsed }
|
|
func (attempt AssessmentAttempt) MaxSessions() int32 { return attempt.snapshot.MaxSessions }
|
|
func (attempt AssessmentAttempt) IdleTimeoutSeconds() int32 {
|
|
return attempt.snapshot.IdleTimeoutSeconds
|
|
}
|
|
func (attempt AssessmentAttempt) UpdatedAt() time.Time { return attempt.snapshot.UpdatedAt }
|
|
|
|
// Snapshot returns a deep copy for persistence and read projections.
|
|
func (attempt AssessmentAttempt) Snapshot() AssessmentAttemptSnapshot {
|
|
snapshot := attempt.snapshot
|
|
snapshot.Specialization = clonePointer(snapshot.Specialization)
|
|
snapshot.TargetGrade = clonePointer(snapshot.TargetGrade)
|
|
snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage)
|
|
snapshot.Items = slices.Clone(snapshot.Items)
|
|
for index := range snapshot.Items {
|
|
snapshot.Items[index].Variant = cloneAssessmentVariant(snapshot.Items[index].Variant)
|
|
snapshot.Items[index].Answer = bytes.Clone(snapshot.Items[index].Answer)
|
|
}
|
|
return snapshot
|
|
}
|
|
|
|
// PublicSnapshot returns only the fields a candidate may receive. It is safe
|
|
// to retain as an idempotency response and to serialize at the HTTP boundary.
|
|
func (attempt AssessmentAttempt) PublicSnapshot() AssessmentAttemptPublicSnapshot {
|
|
snapshot := attempt.snapshot
|
|
public := AssessmentAttemptPublicSnapshot{
|
|
ID: attempt.ID(), Version: snapshot.Version, Kind: snapshot.Kind, Mode: snapshot.Mode,
|
|
State: snapshot.State, Specialization: clonePointer(snapshot.Specialization),
|
|
TargetGrade: clonePointer(snapshot.TargetGrade), TaskLanguage: clonePointer(snapshot.TaskLanguage),
|
|
PolicyVersion: snapshot.Versions.ProductPolicyVersion, BankVersion: snapshot.Versions.BankVersion,
|
|
AlgorithmVersion: snapshot.Versions.AlgorithmVersion, StartedAt: snapshot.CreatedAt, ExpiresAt: snapshot.ExpiresAt,
|
|
MaxItems: boundedAssessmentItemCount(len(snapshot.Items)),
|
|
SessionsUsed: snapshot.SessionsUsed, MaxSessions: snapshot.MaxSessions,
|
|
IdleTimeout: snapshot.IdleTimeoutSeconds, Practices: []AssessmentAttemptPublicPractice{},
|
|
}
|
|
if snapshot.Kind == AssessmentAttemptKindCorrective {
|
|
rootID, deadline := snapshot.RootAttemptID, snapshot.ChainDeadline
|
|
public.RootAttemptID = &rootID
|
|
public.ChainDeadline = &deadline
|
|
}
|
|
if !snapshot.EndedAt.IsZero() {
|
|
finishedAt := snapshot.EndedAt
|
|
public.FinishedAt = &finishedAt
|
|
}
|
|
for _, item := range snapshot.Items {
|
|
if len(item.Answer) > 0 {
|
|
public.AnsweredItems++
|
|
continue
|
|
}
|
|
if snapshot.State == AssessmentAttemptStateInProgress && public.CurrentItem == nil {
|
|
content, ok := publicItemContent(item.Variant)
|
|
if ok {
|
|
public.CurrentItem = &AssessmentAttemptPublicItem{
|
|
ID: item.ID, Sequence: item.Ordinal, Prompt: item.Variant.Statement, Content: content,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return public
|
|
}
|
|
|
|
// PendingItemIDs returns the unanswered frozen item IDs in presentation order.
|
|
// It is used only for the bounded finalize state-conflict response.
|
|
func (attempt AssessmentAttempt) PendingItemIDs() []uuid.UUID {
|
|
if attempt.IsZero() {
|
|
return nil
|
|
}
|
|
ids := make([]uuid.UUID, 0, len(attempt.snapshot.Items))
|
|
for _, item := range attempt.snapshot.Items {
|
|
if len(item.Answer) == 0 {
|
|
ids = append(ids, item.ID)
|
|
}
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func publicItemContent(variant AssessmentVariant) (AssessmentAttemptPublicItemContent, bool) {
|
|
switch variant.AnswerFormat {
|
|
case AnswerFormatInteger:
|
|
return AssessmentAttemptPublicItemContent{Format: "number"}, true
|
|
case AnswerFormatChoice:
|
|
if !validFrozenChoiceVariant(variant) {
|
|
return AssessmentAttemptPublicItemContent{}, false
|
|
}
|
|
// Only the opaque IDs and the texts leave the server: the index of
|
|
// the correct option and the way the distractors were made do not.
|
|
options := make([]AssessmentAttemptPublicOption, 0, len(variant.Options))
|
|
for _, option := range variant.Options {
|
|
options = append(options, AssessmentAttemptPublicOption(option))
|
|
}
|
|
return AssessmentAttemptPublicItemContent{Format: AnswerFormatChoice, Elements: options}, true
|
|
case AnswerFormatIntegerSequence:
|
|
taskCount, ok := variant.Parameters["tasks"]
|
|
if !ok || taskCount < 2 || taskCount > 20 {
|
|
return AssessmentAttemptPublicItemContent{}, false
|
|
}
|
|
elements := make([]AssessmentAttemptPublicOption, 0, taskCount)
|
|
for task := int32(1); task <= taskCount; task++ {
|
|
elements = append(elements, AssessmentAttemptPublicOption{
|
|
ID: fmt.Sprintf("job_%d", task), Text: fmt.Sprintf("%d", task),
|
|
})
|
|
}
|
|
return AssessmentAttemptPublicItemContent{Format: "order", Elements: elements}, true
|
|
default:
|
|
return AssessmentAttemptPublicItemContent{}, false
|
|
}
|
|
}
|
|
|
|
// RestoreAssessmentAttemptPublicSnapshot validates the typed allowlisted
|
|
// response retained for idempotent replay and returns detached pointer data.
|
|
func RestoreAssessmentAttemptPublicSnapshot(
|
|
snapshot AssessmentAttemptPublicSnapshot,
|
|
) (AssessmentAttemptPublicSnapshot, error) {
|
|
const location = "domain.RestoreAssessmentAttemptPublicSnapshot"
|
|
snapshot.StartedAt = canonicalAssessmentTime(snapshot.StartedAt)
|
|
snapshot.ExpiresAt = canonicalAssessmentTime(snapshot.ExpiresAt)
|
|
snapshot.FinishedAt = clonePointer(snapshot.FinishedAt)
|
|
if snapshot.FinishedAt != nil {
|
|
finishedAt := canonicalAssessmentTime(*snapshot.FinishedAt)
|
|
snapshot.FinishedAt = &finishedAt
|
|
}
|
|
snapshot.ChainDeadline = clonePointer(snapshot.ChainDeadline)
|
|
if snapshot.ChainDeadline != nil {
|
|
deadline := canonicalAssessmentTime(*snapshot.ChainDeadline)
|
|
snapshot.ChainDeadline = &deadline
|
|
}
|
|
snapshot.Specialization = clonePointer(snapshot.Specialization)
|
|
snapshot.TargetGrade = clonePointer(snapshot.TargetGrade)
|
|
snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage)
|
|
if snapshot.Practices == nil {
|
|
snapshot.Practices = []AssessmentAttemptPublicPractice{}
|
|
}
|
|
if !validAssessmentAttemptPublicSnapshot(snapshot) {
|
|
return AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - snapshot is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func validAssessmentAttemptPublicSnapshot(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
if !validAssessmentAttemptPublicIdentity(snapshot) || !validAssessmentAttemptPublicProgress(snapshot) {
|
|
return false
|
|
}
|
|
return validAssessmentAttemptPublicTrack(snapshot) && validAssessmentAttemptPublicState(snapshot) &&
|
|
validAssessmentAttemptPublicCurrentItem(snapshot)
|
|
}
|
|
|
|
func validAssessmentAttemptPublicIdentity(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
return !snapshot.ID.IsZero() && snapshot.Version >= 1 && snapshot.PolicyVersion >= 1 &&
|
|
assessmentVersionLabelPattern.MatchString(snapshot.BankVersion) &&
|
|
assessmentVersionLabelPattern.MatchString(snapshot.AlgorithmVersion) &&
|
|
!snapshot.StartedAt.IsZero() && !snapshot.ExpiresAt.IsZero() && snapshot.ExpiresAt.After(snapshot.StartedAt)
|
|
}
|
|
|
|
func validAssessmentAttemptPublicProgress(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
return snapshot.IdleTimeout >= 60 && snapshot.IdleTimeout <= maxAssessmentIdleTimeoutSeconds &&
|
|
snapshot.MaxSessions >= 1 && snapshot.MaxSessions <= maxAssessmentSessions &&
|
|
snapshot.SessionsUsed >= 1 && snapshot.SessionsUsed <= snapshot.MaxSessions &&
|
|
snapshot.MaxItems >= 1 && snapshot.MaxItems <= 100 &&
|
|
snapshot.AnsweredItems >= 0 && snapshot.AnsweredItems <= snapshot.MaxItems &&
|
|
len(snapshot.Practices) == 0
|
|
}
|
|
|
|
func validAssessmentAttemptPublicCurrentItem(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
if snapshot.CurrentItem == nil {
|
|
return snapshot.State != AssessmentAttemptStateInProgress || snapshot.AnsweredItems == snapshot.MaxItems
|
|
}
|
|
item := snapshot.CurrentItem
|
|
return snapshot.State == AssessmentAttemptStateInProgress && snapshot.AnsweredItems < snapshot.MaxItems &&
|
|
item.ID != uuid.Nil && item.Sequence >= 1 && item.Sequence <= snapshot.MaxItems &&
|
|
item.Prompt != "" && len(item.Prompt) <= maxStatementBytes && utf8.ValidString(item.Prompt) &&
|
|
validAssessmentAttemptPublicItemContent(item.Content)
|
|
}
|
|
|
|
func boundedAssessmentItemCount(count int) int32 {
|
|
if count < 0 || count > maxAssessmentAttemptItems {
|
|
return 0
|
|
}
|
|
return int32(count)
|
|
}
|
|
|
|
func validAssessmentAttemptPublicTrack(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
switch snapshot.Kind {
|
|
case AssessmentAttemptKindRoot:
|
|
return validPublicRootTrack(snapshot)
|
|
case AssessmentAttemptKindCorrective:
|
|
return validPublicCorrectiveTrack(snapshot)
|
|
case AssessmentAttemptKindDemoExpress:
|
|
return validPublicTrainingTrack(snapshot)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validPublicRootTrack(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
return validPublicRealTrack(snapshot) && snapshot.RootAttemptID == nil && snapshot.ChainDeadline == nil
|
|
}
|
|
|
|
func validPublicCorrectiveTrack(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
if !validPublicRealTrack(snapshot) || snapshot.RootAttemptID == nil || snapshot.RootAttemptID.IsZero() ||
|
|
snapshot.ChainDeadline == nil {
|
|
return false
|
|
}
|
|
return snapshot.ChainDeadline.After(snapshot.StartedAt) && !snapshot.ExpiresAt.After(*snapshot.ChainDeadline)
|
|
}
|
|
|
|
func validPublicTrainingTrack(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
return snapshot.Mode == AssessmentAttemptModeDemoExpress && snapshot.TaskLanguage == nil &&
|
|
snapshot.Specialization == nil && snapshot.TargetGrade == nil && snapshot.RootAttemptID == nil &&
|
|
snapshot.ChainDeadline == nil
|
|
}
|
|
|
|
func validPublicRealTrack(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
return validTaskLanguage(snapshot.TaskLanguage) && snapshot.Specialization != nil && snapshot.Specialization.IsKnown() &&
|
|
snapshot.TargetGrade != nil && snapshot.TargetGrade.IsKnown() &&
|
|
(snapshot.Mode == AssessmentAttemptModeDemoBasic || snapshot.Mode == AssessmentAttemptModeAdaptive)
|
|
}
|
|
|
|
func validAssessmentAttemptPublicState(snapshot AssessmentAttemptPublicSnapshot) bool {
|
|
switch snapshot.State {
|
|
case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending,
|
|
AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize:
|
|
return snapshot.FinishedAt == nil
|
|
case AssessmentAttemptStateCompleted, AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank:
|
|
return snapshot.FinishedAt != nil && !snapshot.FinishedAt.Before(snapshot.StartedAt)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validAssessmentAttemptPublicItemContent(content AssessmentAttemptPublicItemContent) bool {
|
|
switch content.Format {
|
|
case "number":
|
|
return len(content.Elements) == 0 && !content.Multiple && (content.Unit == nil || *content.Unit != "" && len(*content.Unit) <= 32)
|
|
case AnswerFormatChoice:
|
|
return content.Unit == nil && validAssessmentAttemptPublicElements(content.Elements, minChoiceOptions, maxChoiceOptions, assessmentChoiceOptionIDPattern)
|
|
case "order":
|
|
return content.Unit == nil && validAssessmentAttemptPublicElements(content.Elements, 2, 20, assessmentPublicTaskElementIDPattern)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// validAssessmentAttemptPublicElements checks the options of a choice item or
|
|
// the elements of an order item: a bounded count, IDs of the given shape
|
|
// without repeats, and non-empty bounded text.
|
|
func validAssessmentAttemptPublicElements(elements []AssessmentAttemptPublicOption, minCount, maxCount int, idPattern *regexp.Regexp) bool {
|
|
if len(elements) < minCount || len(elements) > maxCount {
|
|
return false
|
|
}
|
|
seen := make(map[string]struct{}, len(elements))
|
|
for _, element := range elements {
|
|
if !idPattern.MatchString(element.ID) || element.Text == "" || len(element.Text) > 2000 || !utf8.ValidString(element.Text) {
|
|
return false
|
|
}
|
|
if _, exists := seen[element.ID]; exists {
|
|
return false
|
|
}
|
|
seen[element.ID] = struct{}{}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (attempt AssessmentAttempt) String() string { return redactedAssessmentAttempt }
|
|
func (attempt AssessmentAttempt) GoString() string { return redactedAssessmentAttempt }
|
|
func (attempt AssessmentAttempt) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedAssessmentAttempt)
|
|
}
|
|
func (attempt AssessmentAttempt) LogValue() slog.Value {
|
|
return slog.GroupValue(
|
|
slog.String("attempt_id", attempt.ID().String()),
|
|
slog.String("kind", string(attempt.Kind())),
|
|
slog.String("state", string(attempt.State())),
|
|
slog.Int64("version", attempt.Version()),
|
|
)
|
|
}
|
|
|
|
// StartOrResumeSession starts a fresh work session only after the previous one
|
|
// became idle. An active-session repeat is a no-op. Reads never call this
|
|
// method, so polling cannot consume a session or advance the version.
|
|
func (attempt AssessmentAttempt) StartOrResumeSession(expectedVersion int64, at time.Time) (AssessmentAttempt, bool, error) {
|
|
const location = "AssessmentAttempt.StartOrResumeSession"
|
|
if attempt.IsZero() || at.IsZero() {
|
|
return AssessmentAttempt{}, false, fmt.Errorf("%s - invalid attempt or time: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
if expectedVersion != attempt.snapshot.Version {
|
|
return AssessmentAttempt{}, false, fmt.Errorf("%s - expected version is stale: %w", location, ErrAssessmentAttemptVersionConflict)
|
|
}
|
|
if !isAssessmentAttemptActive(attempt.snapshot.State) {
|
|
return attempt, false, nil
|
|
}
|
|
if at.Before(attempt.snapshot.LastActivityAt) {
|
|
return AssessmentAttempt{}, false, fmt.Errorf("%s - time predates last activity: %w", location, ErrInvalidAssessmentAttempt)
|
|
}
|
|
// Only in-progress attempts can expire through a session command. Pending
|
|
// practice and finalization states need their own lifecycle transition so a
|
|
// session request cannot erase a result that another command must resolve.
|
|
if attempt.snapshot.State != AssessmentAttemptStateInProgress {
|
|
return attempt, false, nil
|
|
}
|
|
next := attempt.Snapshot()
|
|
nextAt := canonicalAssessmentTime(at)
|
|
if !nextAt.Before(next.ExpiresAt) || !next.ChainDeadline.IsZero() && !nextAt.Before(next.ChainDeadline) || next.SessionsUsed >= next.MaxSessions && !nextAt.Before(next.LastActivityAt.Add(time.Duration(next.IdleTimeoutSeconds)*time.Second)) {
|
|
next.State = AssessmentAttemptStateExpired
|
|
next.EndedAt = nextAt
|
|
next.UpdatedAt = nextAt
|
|
next.Version++
|
|
updated, err := RestoreAssessmentAttempt(next)
|
|
return updated, true, err
|
|
}
|
|
idleAt := next.LastActivityAt.Add(time.Duration(next.IdleTimeoutSeconds) * time.Second)
|
|
if nextAt.Before(idleAt) {
|
|
return attempt, false, nil
|
|
}
|
|
next.SessionsUsed++
|
|
next.SessionStartedAt = nextAt
|
|
next.LastActivityAt = nextAt
|
|
next.UpdatedAt = nextAt
|
|
next.Version++
|
|
updated, err := RestoreAssessmentAttempt(next)
|
|
return updated, true, err
|
|
}
|
|
|
|
func isAssessmentAttemptActive(state AssessmentAttemptState) bool {
|
|
switch state {
|
|
case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending,
|
|
AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize:
|
|
return true
|
|
case AssessmentAttemptStateCompleted, AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank:
|
|
return false
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func clonePointer[T any](value *T) *T {
|
|
if value == nil {
|
|
return nil
|
|
}
|
|
cloned := *value
|
|
return &cloned
|
|
}
|