Files

267 lines
9.9 KiB
Go

// Package server implements the runner HTTP API on the generated ogen server.
package server
import (
"context"
"errors"
"fmt"
"log/slog"
"math"
"net/http"
"strconv"
"time"
"github.com/google/uuid"
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
"lincodex/runner/internal/api"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/jobs"
"lincodex/runner/internal/judge"
)
// maxRunCPUBudget bounds tests multiplied by the per-test CPU limit, so one
// run cannot hold a sandbox slot for longer than a few minutes.
const maxRunCPUBudget = 300 * time.Second
// Bytes per unit of the contract limits.
const (
bytesPerKB = 1 << 10
bytesPerMB = 1 << 20
)
// Store keeps runs; jobs.Manager implements it.
type Store interface {
Submit(id uuid.UUID, request judge.Request) (jobs.Snapshot, bool, error)
Get(id uuid.UUID) (jobs.Snapshot, error)
}
// Handler implements the generated api.Handler.
type Handler struct {
store Store
supports func(language string) bool
ready func() bool
retryAfter time.Duration
logger *slog.Logger
}
var _ api.Handler = (*Handler)(nil)
// NewHandler returns the API handler.
func NewHandler(store Store, supports func(string) bool, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler {
return &Handler{store: store, supports: supports, ready: ready, retryAfter: retryAfter, logger: logger}
}
// GetRunnerHealthz reports that the process responds.
func (h *Handler) GetRunnerHealthz(context.Context) (*api.RunnerHealthResponse, error) {
return &api.RunnerHealthResponse{Status: api.RunnerHealthResponseStatusOk}, nil
}
// GetRunnerReadyz reports whether the sandbox accepts runs.
func (h *Handler) GetRunnerReadyz(context.Context) (api.GetRunnerReadyzRes, error) {
if h.ready() {
return &api.GetRunnerReadyzOK{Status: api.RunnerReadinessResponseStatusReady}, nil
}
return &api.GetRunnerReadyzServiceUnavailable{Status: api.RunnerReadinessResponseStatusNotReady}, nil
}
// SubmitRun starts a run or returns the run with the same ID and payload.
func (h *Handler) SubmitRun(_ context.Context, req *api.RunRequest, params api.SubmitRunParams) (api.SubmitRunRes, error) {
request, fieldErrors := h.toJudgeRequest(req)
if len(fieldErrors) > 0 {
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", fieldErrors...)
}
snapshot, created, err := h.store.Submit(params.RunID, request)
switch {
case errors.Is(err, jobs.ErrBusy):
retryAfter := int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32))
return &api.RunnerBusyHeaders{
RetryAfter: retryAfter,
Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, "Every sandbox slot is busy. Retry later with the same run ID."),
}, nil
case errors.Is(err, jobs.ErrPayloadMismatch):
return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A run with this ID exists with a different payload.")
case err != nil:
return nil, fmt.Errorf("server.Handler.SubmitRun - submit: %w", err)
}
status := toRunStatus(snapshot)
if created {
accepted := api.SubmitRunAccepted(status)
return &accepted, nil
}
existing := api.SubmitRunOK(status)
return &existing, nil
}
// GetRun returns the state and result of a run.
func (h *Handler) GetRun(_ context.Context, params api.GetRunParams) (*api.RunStatus, error) {
snapshot, err := h.store.Get(params.RunID)
if errors.Is(err, jobs.ErrNotFound) {
return nil, problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The runner holds no run with this ID.")
}
if err != nil {
return nil, fmt.Errorf("server.Handler.GetRun - get: %w", err)
}
status := toRunStatus(snapshot)
return &status, nil
}
// NewError maps errors of handlers and of the security check to problems.
func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
var securityErr *ogenerrors.SecurityError
if errors.As(err, &securityErr) {
return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.")
}
h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err)))
return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
}
// toJudgeRequest converts the request and checks the rules the schema
// cannot express. Field errors never echo submitted values.
func (h *Handler) toJudgeRequest(req *api.RunRequest) (judge.Request, []api.ProblemFieldError) {
var fieldErrors []api.ProblemFieldError
if !h.supports(string(req.Language)) {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/language"))
}
timeLimit := time.Duration(req.Limits.TimeLimitMs) * time.Millisecond
request := judge.Request{
Language: string(req.Language),
Source: req.Source,
Limits: judge.Limits{
TimeLimit: timeLimit,
MemoryBytes: int64(req.Limits.MemoryLimitMB) * bytesPerMB,
OutputBytes: int64(req.Limits.OutputLimitKB) * bytesPerKB,
},
Groups: make([]judge.Group, 0, len(req.Groups)),
}
groupIDs := make(map[api.TestKey]bool, len(req.Groups))
tests := 0
for groupIndex, group := range req.Groups {
groupPointer := "/groups/" + strconv.Itoa(groupIndex)
if groupIDs[group.ID] {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/id"))
}
groupIDs[group.ID] = true
spec, valid := h.toCheckerSpec(group.Checker)
if !valid {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/checker"))
}
converted := judge.Group{
ID: string(group.ID),
Visibility: judge.Visibility(group.Visibility),
Checker: spec,
Tests: make([]judge.Test, 0, len(group.Tests)),
}
testIDs := make(map[api.TestKey]bool, len(group.Tests))
for testIndex, test := range group.Tests {
if testIDs[test.ID] {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/tests/"+strconv.Itoa(testIndex)+"/id"))
}
testIDs[test.ID] = true
converted.Tests = append(converted.Tests, judge.Test{ID: string(test.ID), Input: test.Input, ExpectedOutput: test.ExpectedOutput})
}
tests += len(group.Tests)
request.Groups = append(request.Groups, converted)
}
if time.Duration(tests)*timeLimit > maxRunCPUBudget {
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/limits/time_limit_ms"))
}
return request, fieldErrors
}
// toCheckerSpec converts a checker and reports whether its parameters fit
// its kind: numbers needs a positive tolerance, custom needs a program in a
// supported language, and other kinds take no parameter.
func (h *Handler) toCheckerSpec(source api.Checker) (checker.Spec, bool) {
spec := checker.Spec{
Kind: checker.Kind(source.Kind),
AbsTolerance: source.AbsTolerance.Or(0),
RelTolerance: source.RelTolerance.Or(0),
}
hasTolerance := source.AbsTolerance.IsSet() || source.RelTolerance.IsSet()
if program, ok := source.Program.Get(); ok {
spec.Program = &checker.Program{Language: string(program.Language), Source: program.Source}
}
switch spec.Kind {
case checker.Numbers:
return spec, spec.Program == nil && spec.AbsTolerance+spec.RelTolerance > 0
case checker.Custom:
return spec, !hasTolerance && spec.Program != nil && h.supports(spec.Program.Language)
case checker.Exact, checker.Tokens:
return spec, !hasTolerance && spec.Program == nil
default:
return spec, false
}
}
func toRunStatus(snapshot jobs.Snapshot) api.RunStatus {
status := api.RunStatus{RunID: snapshot.ID, State: api.RunStateRunning}
if snapshot.State != jobs.Finished || snapshot.Result == nil {
return status
}
status.State = api.RunStateFinished
status.Result = api.NewOptRunResult(toRunResult(*snapshot.Result))
return status
}
func toRunResult(result judge.Result) api.RunResult {
converted := api.RunResult{
Outcome: api.RunOutcome(result.Outcome),
Groups: make([]api.GroupResult, 0, len(result.Groups)),
DurationMs: result.Duration.Milliseconds(),
}
if result.Compile != nil {
compile := api.CompileResult{Outcome: api.RunOutcome(result.Compile.Outcome)}
if result.Compile.Diagnostic != "" {
compile.Diagnostic = api.NewOptString(result.Compile.Diagnostic)
}
converted.Compile = api.NewOptCompileResult(compile)
}
for _, group := range result.Groups {
converted.Groups = append(converted.Groups, toGroupResult(group))
}
return converted
}
func toGroupResult(group judge.GroupResult) api.GroupResult {
converted := api.GroupResult{
ID: api.TestKey(group.ID),
Visibility: api.TestVisibility(group.Visibility),
Outcome: api.RunOutcome(group.Outcome),
PassedTests: int32(group.Passed), //nolint:gosec // The contract allows at most 50 tests per group.
TotalTests: int32(group.Total), //nolint:gosec // The contract allows at most 50 tests per group.
Tests: make([]api.TestResult, 0, len(group.Tests)),
}
if len(group.Tests) > 0 {
converted.MaxTimeMs = api.NewOptInt64(group.MaxCPUTime.Milliseconds())
converted.MaxMemoryKB = api.NewOptInt64(group.MaxMemoryKB)
}
for _, test := range group.Tests {
converted.Tests = append(converted.Tests, toTestResult(test))
}
return converted
}
func toTestResult(test judge.TestResult) api.TestResult {
converted := api.TestResult{
ID: api.TestKey(test.ID),
Outcome: api.RunOutcome(test.Outcome),
TimeMs: test.CPUTime.Milliseconds(),
WallTimeMs: test.WallTime.Milliseconds(),
MemoryKB: test.MemoryKB,
}
if test.ExitCode != nil {
converted.ExitCode = api.NewOptInt32(int32(*test.ExitCode)) //nolint:gosec // Exit statuses are below 256.
}
if test.Signal != nil {
converted.Signal = api.NewOptInt32(int32(*test.Signal)) //nolint:gosec // Signal numbers are below 65.
}
if test.Limit != "" {
converted.Limit = api.NewOptTerminationLimit(api.TerminationLimit(test.Limit))
}
if test.Diagnostic != "" {
converted.Diagnostic = api.NewOptString(test.Diagnostic)
}
return converted
}