Files

241 lines
6.0 KiB
Go

// Package jobs keeps runs in memory, enforces the number of concurrent
// sandbox runs, and makes submissions idempotent by run ID.
package jobs
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"lincodex/runner/internal/judge"
)
// State of a run.
type State string
const (
Running State = "running"
Finished State = "finished"
)
var (
// ErrBusy means that every slot is taken or the manager is draining.
ErrBusy = errors.New("every sandbox slot is busy")
// ErrPayloadMismatch means that the run ID exists with another payload.
ErrPayloadMismatch = errors.New("run ID reused with a different payload")
// ErrNotFound means that the manager does not hold the run.
ErrNotFound = errors.New("run not found")
)
// Runner evaluates one request.
type Runner interface {
Run(ctx context.Context, request judge.Request) judge.Result
}
// Snapshot is a copy of a run's state.
type Snapshot struct {
ID uuid.UUID
State State
Result *judge.Result
}
// Config bounds the manager.
type Config struct {
MaxConcurrent int
// ResultTTL is how long a finished run stays readable.
ResultTTL time.Duration
// MaxRetained bounds stored runs, running ones included.
MaxRetained int
}
type job struct {
fingerprint [sha256.Size]byte
state State
result *judge.Result
finishedAt time.Time
}
// Manager owns the runs. Request payloads live only while a run executes;
// a stored run keeps its fingerprint and result.
type Manager struct {
cfg Config
runner Runner
logger *slog.Logger
now func() time.Time
ctx context.Context
cancel context.CancelFunc
running sync.WaitGroup
mu sync.Mutex
jobs map[uuid.UUID]*job
active int
draining bool
}
// NewManager returns a manager. Runs use a context that Close cancels.
func NewManager(cfg Config, runner Runner, logger *slog.Logger) (*Manager, error) {
if cfg.MaxConcurrent <= 0 || cfg.MaxRetained < cfg.MaxConcurrent || cfg.ResultTTL <= 0 {
return nil, errors.New("jobs.NewManager - invalid limits")
}
ctx, cancel := context.WithCancel(context.Background())
return &Manager{
cfg: cfg,
runner: runner,
logger: logger,
now: time.Now,
ctx: ctx,
cancel: cancel,
jobs: make(map[uuid.UUID]*job),
}, nil
}
// Fingerprint is the SHA-256 of the canonical JSON encoding of a request.
// Struct fields encode in declaration order and the request has no maps, so
// equal requests always give equal fingerprints.
func Fingerprint(request judge.Request) ([sha256.Size]byte, error) {
encoded, err := json.Marshal(request)
if err != nil {
return [sha256.Size]byte{}, fmt.Errorf("jobs.Fingerprint - encode: %w", err)
}
return sha256.Sum256(encoded), nil
}
// Submit starts a run or returns the existing run with the same ID and
// payload. created is true when a new run started.
func (m *Manager) Submit(id uuid.UUID, request judge.Request) (snapshot Snapshot, created bool, err error) {
fingerprint, err := Fingerprint(request)
if err != nil {
return Snapshot{}, false, err
}
m.mu.Lock()
defer m.mu.Unlock()
m.forgetExpiredLocked()
if existing, ok := m.jobs[id]; ok {
if existing.fingerprint != fingerprint {
return Snapshot{}, false, ErrPayloadMismatch
}
return existing.snapshot(id), false, nil
}
if m.draining || m.active >= m.cfg.MaxConcurrent {
return Snapshot{}, false, ErrBusy
}
if len(m.jobs) >= m.cfg.MaxRetained && !m.forgetOldestFinishedLocked() {
return Snapshot{}, false, ErrBusy
}
current := &job{fingerprint: fingerprint, state: Running}
m.jobs[id] = current
m.active++
m.running.Go(func() { m.execute(id, current, request) })
return current.snapshot(id), true, nil
}
// Get returns the state of a run.
func (m *Manager) Get(id uuid.UUID) (Snapshot, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.forgetExpiredLocked()
existing, ok := m.jobs[id]
if !ok {
return Snapshot{}, ErrNotFound
}
return existing.snapshot(id), nil
}
// Draining reports whether the manager refuses new runs.
func (m *Manager) Draining() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.draining
}
// Close refuses new runs, waits for running ones until ctx ends, and then
// cancels them, which kills their sandboxes.
func (m *Manager) Close(ctx context.Context) error {
m.mu.Lock()
m.draining = true
m.mu.Unlock()
done := make(chan struct{})
go func() {
m.running.Wait()
close(done)
}()
select {
case <-done:
m.cancel()
return nil
case <-ctx.Done():
m.cancel()
<-done
return fmt.Errorf("jobs.Manager.Close - canceled running runs: %w", ctx.Err())
}
}
func (m *Manager) execute(id uuid.UUID, current *job, request judge.Request) {
m.logger.InfoContext(m.ctx, "run started",
slog.String("run_id", id.String()),
slog.String("language", request.Language),
slog.Int("groups", len(request.Groups)),
slog.Int("tests", countTests(request)),
)
result := m.runner.Run(m.ctx, request)
m.mu.Lock()
current.state = Finished
current.result = &result
current.finishedAt = m.now()
m.active--
m.mu.Unlock()
m.logger.InfoContext(m.ctx, "run finished",
slog.String("run_id", id.String()),
slog.String("outcome", string(result.Outcome)),
slog.Int64("duration_ms", result.Duration.Milliseconds()),
)
}
func (m *Manager) forgetExpiredLocked() {
now := m.now()
for id, existing := range m.jobs {
if existing.state == Finished && now.Sub(existing.finishedAt) > m.cfg.ResultTTL {
delete(m.jobs, id)
}
}
}
func (m *Manager) forgetOldestFinishedLocked() bool {
var oldestID uuid.UUID
var oldest *job
for id, existing := range m.jobs {
if existing.state != Finished {
continue
}
if oldest == nil || existing.finishedAt.Before(oldest.finishedAt) {
oldestID, oldest = id, existing
}
}
if oldest == nil {
return false
}
delete(m.jobs, oldestID)
return true
}
func (j *job) snapshot(id uuid.UUID) Snapshot {
return Snapshot{ID: id, State: j.state, Result: j.result}
}
func countTests(request judge.Request) int {
total := 0
for _, group := range request.Groups {
total += len(group.Tests)
}
return total
}