package postgres import ( "context" "encoding/json" "errors" "fmt" "math" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // Job states the worker side of the practice queue writes. const ( practiceJobFinished = "finished" practiceJobFailed = "failed" ) // PracticeJobStore implements outbound.PracticeJobStore with a pgx pool owned // by the caller. Every method is one short transaction or statement, so no // transaction stays open while the runner works. type PracticeJobStore struct { pool *pgxpool.Pool } var _ outbound.PracticeJobStore = (*PracticeJobStore)(nil) func NewPracticeJobStore(pool *pgxpool.Pool) *PracticeJobStore { return &PracticeJobStore{pool: pool} } func (store *PracticeJobStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { const location = "PracticeJobStore.Claim" if claim.Owner == uuid.Nil || claim.Now.IsZero() || claim.Lease <= 0 || claim.MaxRunning < 1 { return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - owner, now, lease, and running limit must be set") } expiresAt := claim.Now.Add(claim.Lease) var job outbound.ClaimedPracticeJob claimed := false err := store.inTransaction(ctx, func(queries *sqlc.Queries) error { if err := queries.LockAssessmentPracticeQueue(ctx); err != nil { return fmt.Errorf("lock queue: %w", err) } running, err := queries.CountLiveRunningAssessmentPracticeJobs(ctx, timestamp(claim.Now)) if err != nil { return fmt.Errorf("count running jobs: %w", err) } if int(running) >= claim.MaxRunning { return nil } row, err := queries.ClaimAssessmentPracticeJob(ctx, sqlc.ClaimAssessmentPracticeJobParams{ LeaseOwner: pgUUID(claim.Owner), LeaseExpiresAt: timestamp(expiresAt), Now: timestamp(claim.Now), }) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return fmt.Errorf("claim job: %w", err) } mode := domain.PracticeSubmissionMode(row.Mode) if !row.SubmissionID.Valid || !mode.IsKnown() || row.Generation < 0 || row.Attempts < 0 { return fmt.Errorf("claimed job is incomplete: %w", domain.ErrInvalidAssessmentPractice) } job = outbound.ClaimedPracticeJob{ SubmissionID: row.SubmissionID.Bytes, Mode: mode, Generation: uint32(row.Generation), Attempts: int(row.Attempts), LeaseOwner: claim.Owner, LeaseExpiresAt: expiresAt, StartedAt: claim.Now, Reclaimed: row.Reclaimed, } claimed = true return nil }) if err != nil { return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - %w", location, err) } return job, claimed, nil } func (store *PracticeJobStore) Work(ctx context.Context, job outbound.ClaimedPracticeJob) (outbound.PracticeJobWork, error) { const location = "PracticeJobStore.Work" row, err := sqlc.New(store.pool).GetAssessmentPracticeJobWork(ctx, pgUUID(job.SubmissionID)) if err != nil { return outbound.PracticeJobWork{}, fmt.Errorf("%s - read submission: %w", location, sanitizedDatabaseError(err)) } var task domain.PracticeTask if err := json.Unmarshal(row.Task, &task); err != nil { return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode task: %w", location, domain.ErrInvalidAssessmentPractice) } submission := domain.PracticeSubmission{ ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, UserID: row.UserID.Bytes, Mode: domain.PracticeSubmissionMode(row.Mode), Language: domain.TaskLanguageCode(row.Language), Source: row.Source, CreatedAt: row.CreatedAt.Time.UTC(), } if len(row.CustomTests) > 0 { if err := json.Unmarshal(row.CustomTests, &submission.CustomTests); err != nil { return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode custom tests: %w", location, domain.ErrInvalidAssessmentPractice) } } if err := task.Validate(); err != nil { return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate task: %w", location, err) } if err := submission.Validate(task); err != nil { return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate submission: %w", location, err) } return outbound.PracticeJobWork{Submission: submission, Task: task}, nil } func (store *PracticeJobStore) Extend( ctx context.Context, job outbound.ClaimedPracticeJob, expiresAt time.Time, ) (outbound.ClaimedPracticeJob, bool, error) { const location = "PracticeJobStore.Extend" if expiresAt.IsZero() { return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - expiry must be set") } renewed, err := sqlc.New(store.pool).ExtendAssessmentPracticeJobLease(ctx, sqlc.ExtendAssessmentPracticeJobLeaseParams{ LeaseExpiresAt: timestamp(expiresAt), SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), }) if err != nil { return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - renew lease: %w", location, sanitizedDatabaseError(err)) } if renewed != 1 { return outbound.ClaimedPracticeJob{}, false, nil } job.LeaseExpiresAt = expiresAt return job, true, nil } func (store *PracticeJobStore) Requeue(ctx context.Context, job outbound.ClaimedPracticeJob, requeue outbound.PracticeRequeue) (bool, error) { const location = "PracticeJobStore.Requeue" if requeue.AvailableAt.IsZero() || requeue.Generation > math.MaxInt32 { return false, errors.New(location + " - availability must be set and the generation in range") } counted := int32(0) if requeue.Counted { counted = 1 } updated, err := sqlc.New(store.pool).RequeueAssessmentPracticeJob(ctx, sqlc.RequeueAssessmentPracticeJobParams{ AvailableAt: timestamp(requeue.AvailableAt), Generation: int32(requeue.Generation), Counted: counted, ErrorClass: pgOptionalText(string(requeue.ErrorClass)), SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), }) if err != nil { return false, fmt.Errorf("%s - requeue job: %w", location, sanitizedDatabaseError(err)) } return updated == 1, nil } func (store *PracticeJobStore) Complete(ctx context.Context, job outbound.ClaimedPracticeJob, result domain.PracticeRunResult) (bool, error) { const location = "PracticeJobStore.Complete" if err := result.Validate(); err != nil { return false, fmt.Errorf("%s - validate result: %w", location, err) } encoded, err := json.Marshal(result) if err != nil { return false, fmt.Errorf("%s - encode result: %w", location, domain.ErrInvalidAssessmentPractice) } held := false err = store.inTransaction(ctx, func(queries *sqlc.Queries) error { mode, locked, err := lockClaimedPracticeJob(ctx, queries, job) if err != nil || !locked { return err } stored, err := queries.StoreAssessmentPracticeResult(ctx, sqlc.StoreAssessmentPracticeResultParams{ Result: encoded, ID: pgUUID(job.SubmissionID), }) if err != nil { return fmt.Errorf("store result: %w", err) } if stored != 1 { return outbound.ErrPracticeResultExists } if err := finishPracticeJob(ctx, queries, job, practiceJobFinished, ""); err != nil { return err } if mode == domain.PracticeModeFinal { if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFinished, ""); err != nil { return err } } held = true return nil }) if err != nil { return false, fmt.Errorf("%s - %w", location, err) } return held, nil } func (store *PracticeJobStore) Fail(ctx context.Context, job outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (bool, error) { const location = "PracticeJobStore.Fail" if class == "" { return false, errors.New(location + " - error class must be set") } held := false err := store.inTransaction(ctx, func(queries *sqlc.Queries) error { mode, locked, err := lockClaimedPracticeJob(ctx, queries, job) if err != nil || !locked { return err } if err := finishPracticeJob(ctx, queries, job, practiceJobFailed, class); err != nil { return err } if mode == domain.PracticeModeFinal { if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxError); err != nil { return err } } held = true return nil }) if err != nil { return false, fmt.Errorf("%s - %w", location, err) } return held, nil } // lockClaimedPracticeJob locks the job of a try and reports whether the try // still holds it. func lockClaimedPracticeJob( ctx context.Context, queries *sqlc.Queries, job outbound.ClaimedPracticeJob, ) (domain.PracticeSubmissionMode, bool, error) { mode, err := queries.LockClaimedAssessmentPracticeJob(ctx, sqlc.LockClaimedAssessmentPracticeJobParams{ SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), }) if errors.Is(err, pgx.ErrNoRows) { return "", false, nil } if err != nil { return "", false, fmt.Errorf("lock job: %w", err) } return domain.PracticeSubmissionMode(mode), true, nil } func finishPracticeJob( ctx context.Context, queries *sqlc.Queries, job outbound.ClaimedPracticeJob, state string, class outbound.PracticeJobErrorClass, ) error { finished, err := queries.FinishAssessmentPracticeJob(ctx, sqlc.FinishAssessmentPracticeJobParams{ State: state, ErrorClass: pgOptionalText(string(class)), SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), }) if err != nil { return fmt.Errorf("finish job: %w", err) } if finished != 1 { return errors.New("finish job: the locked job changed") } return nil } // settlePractice moves the practice of a final submission out of pending. It // changes nothing when a later final submission replaced this one. func settlePractice( ctx context.Context, queries *sqlc.Queries, job outbound.ClaimedPracticeJob, status domain.AssessmentPracticeStatus, reason domain.AssessmentPracticeFailureReason, ) error { if _, err := queries.SettleAssessmentPracticeAfterJob(ctx, sqlc.SettleAssessmentPracticeAfterJobParams{ Status: string(status), FailureReason: pgOptionalText(string(reason)), SubmissionID: pgUUID(job.SubmissionID), }); err != nil { return fmt.Errorf("settle practice: %w", err) } return nil } // inTransaction runs fn in one READ COMMITTED transaction and keeps only the // SQLSTATE of a database error, whose text could quote submitted code. func (store *PracticeJobStore) inTransaction(ctx context.Context, fn func(queries *sqlc.Queries) error) error { tx, err := store.pool.BeginTx(ctx, transactionOptions) if err != nil { return fmt.Errorf("begin transaction: %w", sanitizeConnectError(err)) } if err := fn(sqlc.New(tx)); err != nil { rollbackErr := rollback(ctx, tx) return errors.Join(sanitizedDatabaseError(err), rollbackErr) } if err := tx.Commit(ctx); err != nil { return fmt.Errorf("commit transaction: %w", sanitizedDatabaseError(err)) } return nil }