Files
lincodex/backend/internal/usecase/practice/service.go
T

624 lines
24 KiB
Go

// 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/hex"
"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
)
// Limits of the practice queue. The runner runs one program at a time, so one
// job runs and ten wait; a command beyond them is answered busy and stores
// nothing.
const (
MaxRunningJobs = 1
MaxQueuedJobs = 10
// queueCapacity counts the running and the queued jobs together, as
// admission sees them: a job counts until it is finished.
queueCapacity = MaxRunningJobs + MaxQueuedJobs
// queueBusyRetryAfter is the wait a full queue announces. Runs take
// seconds, so a slot frees up within it most of the time.
queueBusyRetryAfter = 10 * time.Second
// activeRunRetryAfter is the wait announced while the previous debug run
// of the practice is unfinished.
activeRunRetryAfter = 2 * time.Second
// maxActiveRunsPerPractice keeps one candidate from filling the queue
// with debug runs of one practice.
maxActiveRunsPerPractice = 1
// runBucketLabel separates the rate limit counters of debug runs from
// other uses of the keyed digest.
runBucketLabel = "lincodex/practice/run-bucket/v1"
)
// 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")
// ErrQueueBusy reports that the practice queue is full. Nothing was
// stored; RetryError carries the wait.
ErrQueueBusy = errors.New("practice queue is full")
// ErrRateLimited reports a debug run beyond the technical limits: the
// rate limit of the candidate, or an unfinished run of the practice.
// Nothing was stored; RetryError carries the wait.
ErrRateLimited = errors.New("practice run limit reached")
)
// RetryError is a refusal that a later retry can pass, with the wait the
// caller announces.
type RetryError struct {
Err error
RetryAfter time.Duration
}
func (retryError *RetryError) Error() string { return retryError.Err.Error() }
func (retryError *RetryError) Unwrap() error { return retryError.Err }
// 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
// limiter and runRules bound the debug runs of one candidate; without a
// limiter only the queue limits apply.
limiter outbound.RateLimiter
runRules []outbound.RateLimitRule
}
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
}
// WithRunRateLimit bounds the debug runs of one candidate by the rules, all
// counted at once. A limiter failure refuses the run as unavailable.
func (service *Service) WithRunRateLimit(limiter outbound.RateLimiter, rules ...outbound.RateLimitRule) *Service {
service.limiter, service.runRules = limiter, rules
return service
}
// 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
// RetryAfter is set when the queue was full: the practice is failed with
// sandbox_busy, the solution was not stored, and it can be submitted
// again after the wait.
RetryAfter time.Duration
}
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 := service.admitRun(ctx, repository, command.ActorID, practice.ID); err != nil {
return RunResult{}, fmt.Errorf("%s - admit run: %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)
}
active, err := repository.LockQueue(ctx)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - lock queue: %w", location, err)
}
if active >= queueCapacity {
// The full queue consumes nothing: the solution is not stored, and
// the failed practice accepts it again.
practice.Status, practice.FailureReason, practice.SubmittedAt =
domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxBusy, now
if err := repository.SaveState(ctx, practice, now); err != nil {
return FinalResult{}, fmt.Errorf("%s - mark practice busy: %w", location, err)
}
return FinalResult{Practice: practice.View(), RetryAfter: queueBusyRetryAfter}, nil
}
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
}
// admitRun applies the limits of a debug run in its transaction, which holds
// the practice lock: one unfinished run per practice, the rate limit of the
// candidate, then the queue capacity under the queue lock. A refusal stores
// nothing.
func (service *Service) admitRun(
ctx context.Context,
repository outbound.AssessmentPracticeRepository,
actorID uuid.UUID,
practiceID uuid.UUID,
) error {
const location = "Service.admitRun"
running, err := repository.ActiveRuns(ctx, practiceID)
if err != nil {
return fmt.Errorf("%s - count unfinished runs: %w", location, err)
}
if running >= maxActiveRunsPerPractice {
return fmt.Errorf("%s - a run of the practice is unfinished: %w", location,
&RetryError{Err: ErrRateLimited, RetryAfter: activeRunRetryAfter})
}
if service.limiter != nil {
digest := service.keyring.Fingerprint([]byte(runBucketLabel + "\x00" + actorID.String()))
decision, err := service.limiter.Take(ctx, "practice:run:"+hex.EncodeToString(digest[:]), service.runRules...)
if err != nil {
return fmt.Errorf("%s - take rate limit: %w: %w", location, ErrUnavailable, err)
}
if !decision.Allowed {
return fmt.Errorf("%s - rate limit reached: %w", location,
&RetryError{Err: ErrRateLimited, RetryAfter: decision.RetryAfter})
}
}
active, err := repository.LockQueue(ctx)
if err != nil {
return fmt.Errorf("%s - lock queue: %w", location, err)
}
if active >= queueCapacity {
return fmt.Errorf("%s - queue is full: %w", location, &RetryError{Err: ErrQueueBusy, RetryAfter: queueBusyRetryAfter})
}
return 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
}