Files
lincodex/backend/internal/worker/practicequeue/worker.go
T

133 lines
5.0 KiB
Go

// Package practicequeue runs the practice queue: it claims one practice job
// at a time under a lease and hands it to the practice executor, which runs
// it on the code runner. The queue is not the scheduled job runtime because a
// practice try waits for an external run for seconds or minutes, while a
// scheduled job runs its handler inside the transaction that completes it;
// here no transaction stays open while the runner works.
package practicequeue
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/practice"
"lincodex/backend/internal/worker/retry"
)
// Executor runs one claimed job.
type Executor interface {
Execute(ctx context.Context, job outbound.ClaimedPracticeJob) (practice.ExecutionOutcome, error)
}
// Settings are the worker limits; config validates their ranges.
type Settings struct {
// PollInterval is the wait after a pass that found nothing to run.
PollInterval time.Duration
// Lease is how long a claimed job belongs to this worker before another
// may take it over; the executor renews it while the run lasts.
Lease time.Duration
// StoreTimeout bounds one claim.
StoreTimeout time.Duration
// Backoff spaces passes while the database fails.
Backoff retry.Backoff
}
func (settings Settings) validate() error {
if settings.PollInterval <= 0 || settings.Lease <= 0 || settings.StoreTimeout <= 0 ||
settings.Backoff.Initial <= 0 || settings.Backoff.Max < settings.Backoff.Initial {
return errors.New("practicequeue.New - poll interval, lease, store timeout, and backoff must be positive")
}
return nil
}
// Worker claims practice jobs. Several workers may run against one database:
// the claim keeps at most practice.MaxRunningJobs jobs running across all of
// them.
type Worker struct {
owner uuid.UUID
store outbound.PracticeJobStore
executor Executor
logger *slog.Logger
settings Settings
clock func() time.Time
}
// New builds a worker with a random lease owner ID. clock is the application
// clock that every lease decision uses.
func New(store outbound.PracticeJobStore, executor Executor, logger *slog.Logger, settings Settings, clock func() time.Time) (*Worker, error) {
if store == nil || executor == nil || logger == nil || clock == nil {
return nil, errors.New("practicequeue.New - store, executor, logger, and clock are required")
}
if err := settings.validate(); err != nil {
return nil, err
}
owner := uuid.New()
return &Worker{
owner: owner, store: store, executor: executor, settings: settings, clock: clock,
logger: logger.With(slog.String("lease_owner", owner.String())),
}, nil
}
// RunOnce claims one job and runs it. claimed is false when nothing could be
// claimed: the queue is empty, nothing is available yet, or the running limit
// is reached. Tests call it to drive the queue step by step; Run repeats it.
func (worker *Worker) RunOnce(ctx context.Context) (outcome practice.ExecutionOutcome, claimed bool, err error) {
claimCtx, cancel := context.WithTimeout(ctx, worker.settings.StoreTimeout)
job, claimed, err := worker.store.Claim(claimCtx, outbound.PracticeJobClaim{
Owner: worker.owner, Now: worker.clock(), Lease: worker.settings.Lease, MaxRunning: practice.MaxRunningJobs,
})
cancel()
if err != nil {
return "", false, fmt.Errorf("Worker.RunOnce - claim job: %w", err)
}
if !claimed {
return "", false, nil
}
if job.Reclaimed {
worker.logger.Info("practice job taken over after its lease expired",
slog.String("submission_id", job.SubmissionID.String()), slog.Int("attempts", job.Attempts))
}
outcome, err = worker.executor.Execute(ctx, job)
if err != nil {
return outcome, true, fmt.Errorf("Worker.RunOnce - execute job: %w", err)
}
return outcome, true, nil
}
// Run claims and runs jobs until ctx ends. After a pass that ran a job the
// next claim follows at once; otherwise the worker waits PollInterval, and
// after a database failure Backoff, which grows across consecutive failures.
// A job in progress when ctx ends is given back to the queue unfinished.
func (worker *Worker) Run(ctx context.Context) {
worker.logger.Info("practice queue worker started",
slog.Duration("poll_interval", worker.settings.PollInterval), slog.Duration("lease", worker.settings.Lease))
defer worker.logger.Info("practice queue worker stopped")
failures := 0
for ctx.Err() == nil {
outcome, claimed, err := worker.RunOnce(ctx)
var delay time.Duration
switch {
case err != nil && ctx.Err() == nil:
failures++
delay = worker.settings.Backoff.Delay(failures)
worker.logger.Warn("practice queue pass failed in the database; the job is released or waits for its lease",
slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err))
case claimed:
failures = 0
worker.logger.Debug("practice job try ended", slog.String("outcome", string(outcome)))
default:
failures = 0
delay = worker.settings.PollInterval
}
if delay > 0 && !retry.Wait(ctx, delay) {
return
}
}
}