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,210 @@
package v1
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/practice"
)
// PracticeOperations serves the debug runs of code practices.
type PracticeOperations interface {
SubmitRun(ctx context.Context, command practice.RunCommand) (practice.RunResult, error)
GetRun(ctx context.Context, actorID uuid.UUID, attemptID domain.AssessmentAttemptID, runID uuid.UUID) (domain.PracticeRunView, error)
}
// PracticeHandler binds the practice usecases to the v1 API.
type PracticeHandler struct {
operations PracticeOperations
}
func NewPracticeHandler(operations PracticeOperations) *PracticeHandler {
if operations == nil {
panic("v1.NewPracticeHandler - operations must not be nil")
}
return &PracticeHandler{operations: operations}
}
func (handler *Handler) CreateMyAssessmentPracticeRun(
ctx context.Context,
request *api.PracticeRunCreate,
params api.CreateMyAssessmentPracticeRunParams,
) (api.CreateMyAssessmentPracticeRunRes, error) {
if handler.practice == nil {
return handler.UnimplementedHandler.CreateMyAssessmentPracticeRun(ctx, request, params)
}
return handler.practice.CreateMyAssessmentPracticeRun(ctx, request, params)
}
func (handler *Handler) GetMyAssessmentPracticeRun(
ctx context.Context,
params api.GetMyAssessmentPracticeRunParams,
) (api.GetMyAssessmentPracticeRunRes, error) {
if handler.practice == nil {
return handler.UnimplementedHandler.GetMyAssessmentPracticeRun(ctx, params)
}
return handler.practice.GetMyAssessmentPracticeRun(ctx, params)
}
func (handler *PracticeHandler) CreateMyAssessmentPracticeRun(
ctx context.Context,
request *api.PracticeRunCreate,
params api.CreateMyAssessmentPracticeRunParams,
) (api.CreateMyAssessmentPracticeRunRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
command := practice.RunCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
PracticeID: uuid.UUID(request.ItemID), IdempotencyKey: params.IdempotencyKey, Source: request.SourceCode,
Tests: make([]domain.PracticeTest, 0, len(request.Tests)),
}
if !request.Language.Null {
language := domain.TaskLanguageCode(request.Language.Value)
command.Language = &language
}
for _, test := range request.Tests {
command.Tests = append(command.Tests, domain.PracticeTest{Input: test.Input, ExpectedOutput: test.ExpectedOutput})
}
result, err := handler.operations.SubmitRun(ctx, command)
if err != nil {
return practiceRunFailure(ctx, err)
}
response, err := practiceRunResponse(result.Run)
if err != nil {
return nil, fmt.Errorf("PracticeHandler.CreateMyAssessmentPracticeRun - map run: %w", err)
}
return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *PracticeHandler) GetMyAssessmentPracticeRun(
ctx context.Context,
params api.GetMyAssessmentPracticeRunParams,
) (api.GetMyAssessmentPracticeRunRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
run, err := handler.operations.GetRun(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID), params.RunID)
switch {
case errors.Is(err, practice.ErrForbidden):
return (*api.GetMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, practice.ErrNotFound):
return (*api.GetMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case err != nil:
return nil, err
}
response, err := practiceRunResponse(run)
if err != nil {
return nil, fmt.Errorf("PracticeHandler.GetMyAssessmentPracticeRun - map run: %w", err)
}
return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func practiceRunFailure(ctx context.Context, err error) (api.CreateMyAssessmentPracticeRunRes, error) {
var fieldError *practice.FieldError
switch {
case errors.As(err, &fieldError):
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/"+fieldError.Field).Response), nil
case errors.Is(err, practice.ErrInvalidKey):
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, practice.ErrForbidden):
return (*api.CreateMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, practice.ErrUnavailable):
unavailable := problem.New(ctx, api.ProblemCodeServiceUnavailable)
return &api.ServiceUnavailableHeaders{Response: unavailable.Response}, nil
case errors.Is(err, practice.ErrKeyReused):
return (*api.CreateMyAssessmentPracticeRunUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, practice.ErrNotFound):
return (*api.CreateMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, practice.ErrStateConflict):
return (*api.CreateMyAssessmentPracticeRunConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
default:
return nil, err
}
}
// practiceRunResponse maps a run to its public form. It reads only the public
// groups of the result, so a hidden group could never reach the response
// even if one were stored with a debug run.
func practiceRunResponse(run domain.PracticeRunView) (api.PracticeRun, error) {
response := api.PracticeRun{
ID: run.ID, ItemID: api.AssessmentItemId(run.PracticeID), CreatedAt: api.Timestamp(run.CreatedAt.UTC()),
FinishedAt: api.NilTimestamp{Null: true}, FailureReason: api.NilPracticeFailureReason{Null: true},
Result: api.NilPracticeRunResult{Null: true},
}
switch run.State {
case domain.PracticeJobQueued:
response.State = api.PracticeRunStateQueued
case domain.PracticeJobRunning:
response.State = api.PracticeRunStateRunning
case domain.PracticeJobFinished:
response.State = api.PracticeRunStateFinished
case domain.PracticeJobFailed:
response.State = api.PracticeRunStateFailed
response.FailureReason = api.NewNilPracticeFailureReason(api.PracticeFailureReasonSandboxError)
default:
return api.PracticeRun{}, errors.New("v1.practiceRunResponse - run state is unknown")
}
if run.FinishedAt != nil {
response.FinishedAt = api.NewNilTimestamp(api.Timestamp(run.FinishedAt.UTC()))
}
if run.State == domain.PracticeJobFinished && run.Result != nil {
result, err := practiceRunResultResponse(run.Result.Public())
if err != nil {
return api.PracticeRun{}, err
}
response.Result = api.NewNilPracticeRunResult(result)
}
return response, nil
}
func practiceRunResultResponse(result domain.PracticeRunResult) (api.PracticeRunResult, error) {
response := api.PracticeRunResult{
Outcome: api.PracticeRunOutcome(result.Outcome), CompileDiagnostic: api.NilString{Null: true},
Tests: []api.PracticeRunTestResult{},
}
if result.CompileDiagnostic != "" {
response.CompileDiagnostic = api.NewNilString(result.CompileDiagnostic)
}
for _, group := range result.Groups {
var source api.PracticeRunTestSource
switch {
case group.Hidden:
continue
case group.ID == practice.PublicGroupID:
source = api.PracticeRunTestSourceExample
case group.ID == practice.CustomGroupID:
source = api.PracticeRunTestSourceCandidate
default:
return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - group is unknown")
}
for _, test := range group.Tests {
index, err := strconv.ParseInt(test.ID, 10, 32)
if err != nil || index < 1 {
return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - test index is invalid")
}
item := api.PracticeRunTestResult{
Source: source, Index: int32(index), Outcome: api.PracticeRunOutcome(test.Outcome),
TimeMs: test.TimeMs, MemoryKB: test.MemoryKB, Diagnostic: api.NilString{Null: true},
}
if diagnostic := strings.TrimSpace(test.Diagnostic); diagnostic != "" {
item.Diagnostic = api.NewNilString(test.Diagnostic)
}
response.Tests = append(response.Tests, item)
}
}
return response, nil
}