feat(practice): store code submissions and practice states apart from attempts

This commit is contained in:
shira committed 2026-10-11 14:58:04 +03:00
1 parent d5e169e71b
commit 51770eea6c
61 files changed
+8584 -135

No files matched your search

@@ -0,0 +1,103 @@
package practice
import (
"fmt"
"strconv"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Group IDs of a run request. They are opaque labels for the runner and the
// stored result; the hidden ones never reach a candidate.
const (
// PublicGroupID holds the public examples of the task.
PublicGroupID = "public"
// CustomGroupID holds the candidate's own tests of a debug run.
CustomGroupID = "custom"
// hiddenGroupPrefix is followed by the group number, from 1.
hiddenGroupPrefix = "hidden-"
)
// RunRequest builds the runner request of a submission. A debug run carries
// the public examples and the candidate's own tests, never a hidden group; a
// final submission carries the hidden groups only, which grade it. The key
// binds the run to the practice item, the submission, and the generation, so
// a retry reuses the run and a new generation starts a new one.
func RunRequest(task domain.PracticeTask, submission domain.PracticeSubmission, generation uint32) (outbound.CodeRunRequest, error) {
const location = "practice.RunRequest"
language, err := runnerLanguage(submission.Language)
if err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - map language: %w", location, err)
}
checker, err := runnerChecker(task.Checker)
if err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - map checker: %w", location, err)
}
request := outbound.CodeRunRequest{
Key: outbound.CodeRunKey{AttemptItemID: submission.PracticeID, SubmissionID: submission.ID, Generation: generation},
Language: language,
Source: submission.Source,
Limits: outbound.CodeRunLimits{
TimeLimitMs: task.TimeLimitMs, MemoryLimitMB: task.MemoryLimitMB, OutputLimitKB: task.OutputLimitKB,
},
}
switch submission.Mode {
case domain.PracticeModePublic:
request.Groups = append(request.Groups, runnerGroup(PublicGroupID, outbound.CodeTestPublic, checker, task.PublicTests))
if len(submission.CustomTests) > 0 {
request.Groups = append(request.Groups, runnerGroup(CustomGroupID, outbound.CodeTestPublic, checker, submission.CustomTests))
}
case domain.PracticeModeFinal:
for index, group := range task.HiddenGroups {
id := hiddenGroupPrefix + strconv.Itoa(index+1)
request.Groups = append(request.Groups, runnerGroup(id, outbound.CodeTestHidden, checker, group.Tests))
}
default:
return outbound.CodeRunRequest{}, fmt.Errorf("%s - mode must be public or final: %w", location, domain.ErrInvalidAssessmentPractice)
}
if err := request.Validate(); err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - validate request: %w", location, err)
}
return request, nil
}
func runnerGroup(
id string,
visibility outbound.CodeTestVisibility,
checker outbound.CodeChecker,
tests []domain.PracticeTest,
) outbound.CodeTestGroup {
group := outbound.CodeTestGroup{ID: id, Visibility: visibility, Checker: checker, Tests: make([]outbound.CodeTest, 0, len(tests))}
for index, test := range tests {
group.Tests = append(group.Tests, outbound.CodeTest{
ID: strconv.Itoa(index + 1), Input: test.Input, ExpectedOutput: test.ExpectedOutput,
})
}
return group
}
func runnerLanguage(language domain.TaskLanguageCode) (outbound.CodeLanguage, error) {
switch language {
case domain.TaskLanguageGo:
return outbound.CodeLanguageGo, nil
case domain.TaskLanguagePython:
return outbound.CodeLanguagePython3, nil
default:
return "", fmt.Errorf("practice.runnerLanguage - language is unknown: %w", domain.ErrInvalidAssessmentPractice)
}
}
func runnerChecker(checker domain.PracticeChecker) (outbound.CodeChecker, error) {
mapped := outbound.CodeChecker{
Kind: outbound.CodeCheckerKind(checker.Kind), AbsTolerance: checker.AbsTolerance, RelTolerance: checker.RelTolerance,
}
if checker.Program != nil {
language, err := runnerLanguage(checker.Program.Language)
if err != nil {
return outbound.CodeChecker{}, fmt.Errorf("practice.runnerChecker - map program language: %w", err)
}
mapped.Program = &outbound.CodeCheckerProgram{Language: language, Source: checker.Program.Source}
}
return mapped, nil
}
@@ -0,0 +1,72 @@
package practice
import (
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const hiddenMarker = "hidden-secret"
func TestRunRequestKeepsHiddenGroupsOutOfDebugRuns(t *testing.T) {
task := testTask()
submission := domain.PracticeSubmission{
ID: uuid.New(), PracticeID: uuid.New(), UserID: uuid.New(), Mode: domain.PracticeModePublic,
Language: domain.TaskLanguagePython, Source: "print(1)\n", CreatedAt: time.Now(),
CustomTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}},
}
request, err := RunRequest(task, submission, 0)
if err != nil {
t.Fatalf("RunRequest(public) error = %v", err)
}
if len(request.Groups) != 2 || request.Groups[0].ID != PublicGroupID || request.Groups[1].ID != CustomGroupID {
t.Fatalf("public groups = %d, want the public and the custom group", len(request.Groups))
}
for _, group := range request.Groups {
if group.Visibility != outbound.CodeTestPublic {
t.Fatalf("group %s visibility = %s, want public", group.ID, group.Visibility)
}
for _, test := range group.Tests {
if strings.Contains(test.Input+test.ExpectedOutput, hiddenMarker) {
t.Fatalf("a debug run carries hidden test content in group %s", group.ID)
}
}
}
if request.Language != outbound.CodeLanguagePython3 || request.Key.AttemptItemID != submission.PracticeID ||
request.Key.SubmissionID != submission.ID {
t.Fatal("request language or key does not match the submission")
}
submission.Mode, submission.CustomTests = domain.PracticeModeFinal, nil
request, err = RunRequest(task, submission, 3)
if err != nil {
t.Fatalf("RunRequest(final) error = %v", err)
}
if len(request.Groups) != domain.PracticeHiddenGroups || request.Key.Generation != 3 {
t.Fatalf("final groups = %d with generation %d, want three hidden groups and generation 3", len(request.Groups), request.Key.Generation)
}
for index, group := range request.Groups {
if group.Visibility != outbound.CodeTestHidden || group.ID != hiddenGroupPrefix+string(rune('1'+index)) {
t.Fatalf("final group %d = %s %s, want a hidden group", index, group.ID, group.Visibility)
}
}
}
func testTask() domain.PracticeTask {
hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups)
for range domain.PracticeHiddenGroups {
hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{Input: hiddenMarker, ExpectedOutput: hiddenMarker}}})
}
return domain.PracticeTask{
Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython},
MaxSourceLength: 100, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64,
Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerExact},
PublicTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}},
HiddenGroups: hidden,
}
}
@@ -0,0 +1,509 @@
// Package practice stores code practice submissions and their execution
// jobs. It keeps practice state apart from the attempt snapshot and the
// result: a submission and its job commit together, and the practice queue
// worker runs the job later.
package practice
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Idempotency operations. Each scopes its keys separately.
const (
runOperation = "assessment_practice.run"
finalOperation = "assessment_practice.final"
// maxIdempotencyKeyBytes is the contract bound of Idempotency-Key.
maxIdempotencyKeyBytes = 255
)
// Request fields that a FieldError names. The HTTP adapter turns them into
// pointers of its own body.
const (
FieldLanguage = "language"
FieldSource = "source_code"
FieldTests = "tests"
)
var (
// ErrInvalidRequest reports a command that breaks the contract or the
// rules of the task; FieldError names the field.
ErrInvalidRequest = errors.New("invalid practice request")
// ErrInvalidKey reports a malformed Idempotency-Key.
ErrInvalidKey = errors.New("invalid practice idempotency key")
// ErrKeyReused reports an Idempotency-Key used with another request.
ErrKeyReused = errors.New("practice idempotency key reused")
// ErrForbidden reports an account that is not a verified candidate.
ErrForbidden = errors.New("practice is for verified candidates only")
// ErrNotFound reports an attempt, practice, or run that is unknown or
// belongs to another candidate.
ErrNotFound = errors.New("practice not found")
// ErrStateConflict reports a command that the attempt or the practice
// does not accept now: the attempt is not at this practice or past its
// deadline, or the practice already has another solution.
ErrStateConflict = errors.New("practice state conflict")
// ErrUnavailable reports that code practice cannot run now, for example
// because the code runner is disabled. Nothing was stored or graded.
ErrUnavailable = errors.New("code practice unavailable")
)
// FieldError names the request field that ErrInvalidRequest is about.
type FieldError struct {
Field string
}
func (fieldError *FieldError) Error() string {
return "invalid practice request field " + fieldError.Field
}
func (fieldError *FieldError) Unwrap() error { return ErrInvalidRequest }
// Keyring computes scoped idempotency digests with the server secret.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Service accepts debug runs and final solutions of code practices.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
// enabled is false when no code runner is configured: practice then
// answers unavailable and stores nothing.
enabled bool
}
func NewService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time, enabled bool) (*Service, error) {
if transactor == nil || keyring == nil || clock == nil {
return nil, errors.New("practice.NewService - transactor, keyring, and clock are required")
}
return &Service{transactor: transactor, keyring: keyring, clock: clock, enabled: enabled}, nil
}
// RunCommand asks for a debug run of a solution against the public examples
// and the candidate's own tests.
type RunCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
PracticeID uuid.UUID
IdempotencyKey string
// Language is nil when the task offers one language only.
Language *domain.TaskLanguageCode
Source string
Tests []domain.PracticeTest
}
// RunResult is the queued or replayed run.
type RunResult struct {
Run domain.PracticeRunView
Replayed bool
}
// FinalCommand submits the solution that the hidden groups grade.
type FinalCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
PracticeID uuid.UUID
IdempotencyKey string
Language *domain.TaskLanguageCode
Source string
}
// FinalResult is the practice state after the command.
type FinalResult struct {
Practice domain.AssessmentPracticeView
// Replayed reports a repeat of an earlier request with the same key.
Replayed bool
// Unchanged reports that the same solution was already submitted and
// nothing was stored.
Unchanged bool
}
type canonicalRequest struct {
PracticeID string `json:"item_id"`
Language *string `json:"language"`
Source string `json:"source_code"`
Tests []domain.PracticeTest `json:"tests,omitempty"`
}
// SubmitRun stores a debug run and queues its job in one transaction. A
// repeat with the same Idempotency-Key and request returns the stored run in
// its current state; refusals are not stored and are evaluated again.
func (service *Service) SubmitRun(ctx context.Context, command RunCommand) (RunResult, error) {
const location = "Service.SubmitRun"
if err := domain.ValidatePracticeCustomTests(command.Tests); err != nil {
return RunResult{}, fmt.Errorf("%s - validate tests: %w", location, &FieldError{Field: FieldTests})
}
request, err := service.prepare(runOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey,
canonicalRequest{Language: languageText(command.Language), Source: command.Source, Tests: command.Tests})
if err != nil {
return RunResult{}, fmt.Errorf("%s - prepare: %w", location, err)
}
var result RunResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var transactionErr error
result, transactionErr = service.submitRunInTransaction(ctx, unit, command, request)
return transactionErr
})
if err != nil {
return RunResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *Service) submitRunInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command RunCommand,
request idempotentRequest,
) (RunResult, error) {
const location = "Service.submitRunInTransaction"
if err := requireCandidate(ctx, unit, command.ActorID); err != nil {
return RunResult{}, fmt.Errorf("%s - check account: %w", location, err)
}
if !service.enabled {
return RunResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable)
}
replayed, err := reserve(ctx, unit, request)
if err != nil {
return RunResult{}, fmt.Errorf("%s - reserve key: %w", location, err)
}
repository := unit.AssessmentPractices()
if replayed {
stored, found, err := repository.FindByScope(ctx, command.ActorID, request.record.Scope)
if err != nil {
return RunResult{}, fmt.Errorf("%s - find replayed run: %w", location, err)
}
if !found || stored.Mode != domain.PracticeModePublic {
return RunResult{}, fmt.Errorf("%s - replayed key has no run: %w", location, ErrKeyReused)
}
run, err := repository.GetRun(ctx, command.ActorID, command.AttemptID, stored.ID)
if err != nil {
return RunResult{}, fmt.Errorf("%s - read replayed run: %w", location, mapNotFound(err))
}
return RunResult{Run: run, Replayed: true}, nil
}
practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return RunResult{}, fmt.Errorf("%s - lock practice: %w", location, err)
}
submission, err := newSubmission(practice, domain.PracticeModePublic, command.ActorID, command.Language, command.Source, command.Tests, now)
if err != nil {
return RunResult{}, fmt.Errorf("%s - build submission: %w", location, err)
}
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
return RunResult{}, fmt.Errorf("%s - store run: %w", location, err)
}
return RunResult{Run: domain.PracticeRunView{
ID: submission.ID, PracticeID: practice.ID, State: domain.PracticeJobQueued, CreatedAt: now,
}}, nil
}
// SubmitFinal stores the final solution of a practice and queues its job in
// one transaction, and marks the practice pending. The same solution sent
// again stores nothing; a different one is refused while the practice is
// pending or finished, so the source of a graded solution never changes. A
// practice that failed in the sandbox accepts a solution again.
func (service *Service) SubmitFinal(ctx context.Context, command FinalCommand) (FinalResult, error) {
const location = "Service.SubmitFinal"
request, err := service.prepare(finalOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey,
canonicalRequest{Language: languageText(command.Language), Source: command.Source})
if err != nil {
return FinalResult{}, fmt.Errorf("%s - prepare: %w", location, err)
}
var result FinalResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var transactionErr error
result, transactionErr = service.submitFinalInTransaction(ctx, unit, command, request)
return transactionErr
})
if err != nil {
return FinalResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *Service) submitFinalInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command FinalCommand,
request idempotentRequest,
) (FinalResult, error) {
const location = "Service.submitFinalInTransaction"
if err := requireCandidate(ctx, unit, command.ActorID); err != nil {
return FinalResult{}, fmt.Errorf("%s - check account: %w", location, err)
}
if !service.enabled {
return FinalResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable)
}
replayed, err := reserve(ctx, unit, request)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - reserve key: %w", location, err)
}
repository := unit.AssessmentPractices()
if replayed {
if _, err := repository.LockAttempt(ctx, command.ActorID, command.AttemptID); err != nil {
return FinalResult{}, fmt.Errorf("%s - lock attempt of replay: %w", location, mapNotFound(err))
}
practice, err := repository.LockPractice(ctx, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - read practice of replay: %w", location, mapNotFound(err))
}
return FinalResult{Practice: practice.View(), Replayed: true}, nil
}
practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - lock practice: %w", location, err)
}
submission, err := newSubmission(practice, domain.PracticeModeFinal, command.ActorID, command.Language, command.Source, nil, now)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - build submission: %w", location, err)
}
if !practice.Status.AcceptsFinalSubmission() {
return finalRepeat(ctx, repository, practice, submission)
}
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
return FinalResult{}, fmt.Errorf("%s - store final submission: %w", location, err)
}
practice.Status, practice.FailureReason, practice.SubmittedAt = domain.AssessmentPracticePending, "", now
if err := repository.SaveState(ctx, practice, now); err != nil {
return FinalResult{}, fmt.Errorf("%s - mark practice pending: %w", location, err)
}
return FinalResult{Practice: practice.View()}, nil
}
// finalRepeat answers a final submission to a pending or finished practice:
// the stored solution sent again changes nothing, anything else conflicts.
func finalRepeat(
ctx context.Context,
repository outbound.AssessmentPracticeRepository,
practice domain.AssessmentPractice,
submission domain.PracticeSubmission,
) (FinalResult, error) {
const location = "practice.finalRepeat"
stored, found, err := repository.LatestFinal(ctx, practice.ID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - read stored solution: %w", location, err)
}
if !found || stored.Language != submission.Language || stored.SourceDigest != domain.DigestPracticeSource(submission.Source) {
return FinalResult{}, fmt.Errorf("%s - practice already has another solution: %w", location, ErrStateConflict)
}
return FinalResult{Practice: practice.View(), Unchanged: true}, nil
}
// GetRun reads a debug run of the owner's attempt.
func (service *Service) GetRun(
ctx context.Context,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
runID uuid.UUID,
) (domain.PracticeRunView, error) {
const location = "Service.GetRun"
if actorID == uuid.Nil || attemptID.IsZero() || runID == uuid.Nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - candidate, attempt, and run IDs are required: %w", location, ErrNotFound)
}
var run domain.PracticeRunView
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, actorID); err != nil {
return err
}
var readErr error
run, readErr = unit.AssessmentPractices().GetRun(ctx, actorID, attemptID, runID)
return mapNotFound(readErr)
})
if err != nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return run, nil
}
type idempotentRequest struct {
record outbound.IdempotencyRecord
}
// prepare checks what a command needs before any database work and derives
// its idempotency record.
func (service *Service) prepare(
operation string,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
practiceID uuid.UUID,
key string,
body canonicalRequest,
) (idempotentRequest, error) {
const location = "Service.prepare"
if actorID == uuid.Nil || attemptID.IsZero() || practiceID == uuid.Nil {
return idempotentRequest{}, fmt.Errorf("%s - candidate, attempt, and practice IDs are required: %w", location, ErrNotFound)
}
if !validIdempotencyKey(key) {
return idempotentRequest{}, fmt.Errorf("%s - check key: %w", location, ErrInvalidKey)
}
if body.Language != nil && !domain.TaskLanguageCode(*body.Language).IsKnown() {
return idempotentRequest{}, fmt.Errorf("%s - check language: %w", location, &FieldError{Field: FieldLanguage})
}
body.PracticeID = practiceID.String()
canonical, err := json.Marshal(body)
if err != nil {
return idempotentRequest{}, fmt.Errorf("%s - encode request fingerprint: %w", location, ErrInvalidRequest)
}
now := service.clock().UTC().Truncate(time.Microsecond)
return idempotentRequest{record: outbound.IdempotencyRecord{
Scope: service.keyring.IdempotencyScope(operation, key, actorID.String()),
Fingerprint: service.keyring.Fingerprint(canonical),
CreatedAt: now,
ExpiresAt: now.Add(outbound.IdempotencyRetention),
}}, nil
}
// requireCandidate admits a verified candidate account only.
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
const location = "practice.requireCandidate"
user, err := unit.Users().GetByID(ctx, actorID)
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - account is missing: %w", location, ErrForbidden)
}
if err != nil {
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
return fmt.Errorf("%s - require a verified candidate: %w", location, ErrForbidden)
}
return nil
}
// reserve takes the idempotency record in the transaction and reports a
// replay of the same request. A concurrent request with the same key waits
// for the first transaction.
func reserve(ctx context.Context, unit outbound.UnitOfWork, request idempotentRequest) (bool, error) {
const location = "practice.reserve"
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return false, fmt.Errorf("%s - reserve record: %w", location, err)
}
if created {
return false, nil
}
if stored.Fingerprint != request.record.Fingerprint {
return false, fmt.Errorf("%s - compare request fingerprint: %w", location, ErrKeyReused)
}
return true, nil
}
// lockOpenPractice locks the attempt and the practice and checks that the
// practice is the current item of a running attempt. It returns the database
// time read under the attempt lock.
func lockOpenPractice(
ctx context.Context,
repository outbound.AssessmentPracticeRepository,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
practiceID uuid.UUID,
) (domain.AssessmentPractice, time.Time, error) {
const location = "practice.lockOpenPractice"
attempt, err := repository.LockAttempt(ctx, actorID, attemptID)
if err != nil {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock attempt: %w", location, mapNotFound(err))
}
practice, err := repository.LockPractice(ctx, actorID, attemptID, practiceID)
if err != nil {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock practice: %w", location, mapNotFound(err))
}
if attempt.State != practice.Kind.AttemptState() || !attempt.DatabaseTime.Before(attempt.ExpiresAt) {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - attempt is not at this practice: %w", location, ErrStateConflict)
}
return practice, attempt.DatabaseTime, nil
}
// newSubmission builds a submission and checks it against the task and the
// runner contract, so the queue never holds a request the runner refuses.
func newSubmission(
practice domain.AssessmentPractice,
mode domain.PracticeSubmissionMode,
actorID uuid.UUID,
language *domain.TaskLanguageCode,
source string,
tests []domain.PracticeTest,
now time.Time,
) (domain.PracticeSubmission, error) {
const location = "practice.newSubmission"
resolved, err := resolveLanguage(practice.Task, language)
if err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - resolve language: %w", location, err)
}
if err := domain.ValidatePracticeSource(source, practice.Task.MaxSourceLength); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - validate source: %w", location, &FieldError{Field: FieldSource})
}
id, err := uuid.NewV7()
if err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - generate submission ID: %w", location, err)
}
submission := domain.PracticeSubmission{
ID: id, PracticeID: practice.ID, UserID: actorID, Mode: mode, Language: resolved, Source: source,
CustomTests: tests, CreatedAt: now,
}
if err := submission.Validate(practice.Task); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - validate submission: %w", location, err)
}
// A task the runner would refuse is a content bug, not the candidate's.
if _, err := RunRequest(practice.Task, submission, 0); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - build run request: %w", location, err)
}
return submission, nil
}
// resolveLanguage returns the submitted language, or the only language of
// the task when none was sent.
func resolveLanguage(task domain.PracticeTask, language *domain.TaskLanguageCode) (domain.TaskLanguageCode, error) {
switch {
case language == nil && len(task.Languages) == 1:
return task.Languages[0], nil
case language != nil && task.AllowsLanguage(*language):
return *language, nil
default:
return "", &FieldError{Field: FieldLanguage}
}
}
func languageText(language *domain.TaskLanguageCode) *string {
if language == nil {
return nil
}
text := string(*language)
return &text
}
func mapNotFound(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, outbound.ErrAssessmentAttemptNotFound), errors.Is(err, outbound.ErrAssessmentPracticeNotFound),
errors.Is(err, outbound.ErrPracticeRunNotFound):
return fmt.Errorf("practice.mapNotFound - %w: %w", ErrNotFound, err)
default:
return err
}
}
func validIdempotencyKey(value string) bool {
if len(value) == 0 || len(value) > maxIdempotencyKeyBytes {
return false
}
for index := range len(value) {
character := value[index]
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9' || character == '.' || character == '_' || character == ':' || character == '-' {
continue
}
return false
}
return true
}