Files

248 lines
10 KiB
Go

package assessment
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const submitAnswerOperation = "assessment_attempt.answer"
// SubmitAttemptAnswerCommand is one candidate answer to the current frozen
// item. The answer is private and must not be logged.
type SubmitAttemptAnswerCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
ItemID uuid.UUID
ExpectedVersion int64
IdempotencyKey string
Answer json.RawMessage
// Origin is the sender of the request. It feeds the server signals only and
// is not part of the idempotency fingerprint.
Origin RequestOrigin
// Client is the identifier of the open page, or empty when the request has
// none. A page that does not hold the work session is refused while another
// page does, and the refusal is not stored under the idempotency key.
Client string
}
type canonicalAttemptAnswerBody struct {
AttemptID string `json:"attempt_id"`
ItemID string `json:"item_id"`
ExpectedVersion int64 `json:"expected_version"`
Answer json.RawMessage `json:"answer"`
}
// SubmitAnswer persists the current answer and an immutable public response in
// one transaction. Raw answer data never enters the idempotency table.
func (service *AttemptService) SubmitAnswer(
ctx context.Context,
command SubmitAttemptAnswerCommand,
) (outbound.AssessmentAttemptCommandResult, error) {
const location = "AttemptService.SubmitAnswer"
if command.ActorID == uuid.Nil {
return outbound.AssessmentAttemptCommandResult{}, ErrAttemptForbidden
}
if command.AttemptID.IsZero() || command.ItemID == uuid.Nil || command.ExpectedVersion < 1 {
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/expected_version", "must be a positive version and identify one item")
}
canonicalAnswer, err := domain.CanonicalAssessmentAnswer(command.Answer)
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/answer", "must match a supported answer format")
}
body, err := json.Marshal(canonicalAttemptAnswerBody{
AttemptID: command.AttemptID.String(), ItemID: command.ItemID.String(), ExpectedVersion: command.ExpectedVersion,
Answer: canonicalAnswer,
})
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(submitAnswerOperation, 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 replayAttemptAnswer(ctx, repository, request, stored, &result)
}
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
return fmt.Errorf("%s - remove expired answer response: %w", location, err)
}
return service.submitNewAnswer(ctx, unit, repository, request.scope, command, &result)
})
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func replayAttemptAnswer(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
request attemptIdempotencyRequest,
stored outbound.IdempotencyRecord,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "assessment.replayAttemptAnswer"
if stored.Fingerprint != request.record.Fingerprint {
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
}
outcome, err := repository.GetAnswerOutcome(ctx, request.scope)
if err != nil {
return fmt.Errorf("%s - read immutable answer response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
return nil
}
func (service *AttemptService) submitNewAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command SubmitAttemptAnswerCommand,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.submitNewAnswer"
current, err := lockAttemptForAnswer(ctx, unit, repository, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 404, result)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if !attemptHasItem(current, command.ItemID) {
return attemptFieldError("/item_id", "does not identify an item in this attempt")
}
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)
if err := service.workSessions.requireHolder(ctx, unit, current, command.Client, databaseTime); err != nil {
return fmt.Errorf("%s - check the holder of the work session: %w", location, err)
}
return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result)
}
func lockAttemptForAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentAttempt, error) {
const location = "AttemptService.lockAttemptForAnswer"
kind, err := repository.GetKindForCandidate(ctx, actorID, 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, actorID, kind); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize answer: %w", location, err)
}
current, err := repository.GetForCandidateForUpdate(ctx, actorID, 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 (service *AttemptService) persistSubmittedAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command SubmitAttemptAnswerCommand,
current domain.AssessmentAttempt,
databaseTime time.Time,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.persistSubmittedAnswer"
updated, changed, submitErr := current.SubmitAnswer(command.ExpectedVersion, command.ItemID, command.Answer, databaseTime)
if submitErr != nil && errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) && command.ExpectedVersion == current.Version() {
expired, expiredChanged, expireErr := current.ExpireIfDue(databaseTime)
if expireErr != nil {
return fmt.Errorf("%s - apply due deadline transition: %w", location, expireErr)
}
if expiredChanged {
if err := repository.SaveTransition(ctx, current, expired); err != nil {
return fmt.Errorf("%s - persist due deadline transition: %w", location, err)
}
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
}
}
if submitErr != nil {
if errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) {
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
}
return mapAttemptAnswerError(submitErr)
}
if changed {
if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil {
return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err)
}
if err := service.signalObserver.observeAnswer(
ctx, unit, current, updated, command.ItemID, command.Origin,
); err != nil {
return fmt.Errorf("%s - observe accepted answer: %w", location, err)
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store immutable answer response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
func attemptHasItem(attempt domain.AssessmentAttempt, itemID uuid.UUID) bool {
for _, item := range attempt.Snapshot().Items {
if item.ID == itemID {
return true
}
}
return false
}
func mapAttemptAnswerError(err error) error {
switch {
case errors.Is(err, domain.ErrAssessmentAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict):
return fmt.Errorf("AttemptService.SubmitAnswer - check expected version: %w", ErrAttemptVersionConflict)
case errors.Is(err, domain.ErrAssessmentAttemptNotActive):
return fmt.Errorf("AttemptService.SubmitAnswer - check answer state: %w", ErrAttemptStateConflict)
case errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return attemptFieldError("/answer", "does not match the current item")
default:
return err
}
}