feat(runner): add the own code runner contract, client and nsjail service
This commit is contained in:
1 parent
5e1db37746
commit
cdf6bcbb91
109 files changed
+24084
-28
No files matched your search
@@ -0,0 +1,237 @@
|
||||
// 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
|
||||
converted := judge.Group{
|
||||
ID: string(group.ID),
|
||||
Visibility: judge.Visibility(group.Visibility),
|
||||
Checker: checker.Spec{Kind: checker.Kind(group.Checker.Kind)},
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
|
||||
"lincodex/runner/internal/api"
|
||||
)
|
||||
|
||||
const problemTypePrefix = "urn:lincodex:problem:"
|
||||
|
||||
// problemTitles are the fixed titles of the runner problem codes.
|
||||
var problemTitles = map[api.ProblemCode]string{
|
||||
api.ProblemCodeValidationFailed: "Request validation failed",
|
||||
api.ProblemCodeUnauthenticated: "Authentication required",
|
||||
api.ProblemCodeNotFound: "Not found",
|
||||
api.ProblemCodeMethodNotAllowed: "Method not allowed",
|
||||
api.ProblemCodePayloadTooLarge: "Payload too large",
|
||||
api.ProblemCodeUnsupportedMediaType: "Unsupported media type",
|
||||
api.ProblemCodeIdempotencyKeyReused: "Run ID reused with a different payload",
|
||||
api.ProblemCodeInternal: "Internal server error",
|
||||
api.ProblemCodeRunnerBusy: "Runner busy",
|
||||
}
|
||||
|
||||
const invalidFieldMessage = "The value does not match the contract."
|
||||
|
||||
func newProblem(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) api.Problem {
|
||||
problem := api.Problem{
|
||||
Type: problemTypePrefix + string(code),
|
||||
Title: problemTitles[code],
|
||||
Status: int32(status), //nolint:gosec // HTTP status codes fit in int32.
|
||||
Code: code,
|
||||
Errors: fieldErrors,
|
||||
}
|
||||
if detail != "" {
|
||||
problem.Detail = api.NewOptString(detail)
|
||||
}
|
||||
return problem
|
||||
}
|
||||
|
||||
func problemError(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) *api.ProblemStatusCode {
|
||||
return &api.ProblemStatusCode{StatusCode: status, Response: newProblem(status, code, detail, fieldErrors...)}
|
||||
}
|
||||
|
||||
func invalidField(in api.ProblemFieldLocation, pointer string) api.ProblemFieldError {
|
||||
return api.ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: invalidFieldMessage}
|
||||
}
|
||||
|
||||
// writeProblem writes a problem outside the generated handlers.
|
||||
func writeProblem(w http.ResponseWriter, problem api.Problem) {
|
||||
encoder := jx.GetEncoder()
|
||||
defer jx.PutEncoder(encoder)
|
||||
problem.Encode(encoder)
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(int(problem.Status))
|
||||
_, _ = w.Write(encoder.Bytes()) // The client may have gone away.
|
||||
}
|
||||
|
||||
// errorHandler answers request decoding errors of the generated server.
|
||||
func errorHandler(logger *slog.Logger) ogenerrors.ErrorHandler {
|
||||
return func(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) {
|
||||
writeProblem(w, decodeProblem(ctx, logger, err))
|
||||
}
|
||||
}
|
||||
|
||||
func decodeProblem(ctx context.Context, logger *slog.Logger, err error) api.Problem {
|
||||
var tooLarge *http.MaxBytesError
|
||||
var contentType *validate.InvalidContentTypeError
|
||||
var paramsErr *ogenerrors.DecodeParamsError
|
||||
var requestErr *ogenerrors.DecodeRequestError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
return newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.")
|
||||
case errors.As(err, &contentType):
|
||||
return newProblem(http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, "Send the body as application/json.")
|
||||
case errors.As(err, ¶msErr):
|
||||
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||
invalidField(api.ProblemFieldLocationPath, "/run_id"))
|
||||
case errors.As(err, &requestErr):
|
||||
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||
invalidField(api.ProblemFieldLocationBody, ""))
|
||||
default:
|
||||
// The error text may describe internals; only its type is logged.
|
||||
logger.ErrorContext(ctx, "request handling failed", slog.String("error_type", fmt.Sprintf("%T", err)))
|
||||
return newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"lincodex/runner/internal/api"
|
||||
)
|
||||
|
||||
var errInvalidToken = errors.New("invalid bearer token")
|
||||
|
||||
// tokenAuth checks the shared service token. Comparing SHA-256 digests in
|
||||
// constant time hides both the content and the length of the token.
|
||||
type tokenAuth struct {
|
||||
digest [sha256.Size]byte
|
||||
}
|
||||
|
||||
func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) {
|
||||
digest := sha256.Sum256([]byte(token.Token))
|
||||
if subtle.ConstantTimeCompare(digest[:], a.digest[:]) != 1 {
|
||||
return ctx, errInvalidToken
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// New returns the HTTP handler of the runner API.
|
||||
func New(handler *Handler, token string, maxRequestBytes int64, logger *slog.Logger) (http.Handler, error) {
|
||||
if token == "" {
|
||||
return nil, errors.New("server.New - empty service token")
|
||||
}
|
||||
generated, err := api.NewServer(handler, tokenAuth{digest: sha256.Sum256([]byte(token))},
|
||||
api.WithErrorHandler(errorHandler(logger)),
|
||||
api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist."))
|
||||
}),
|
||||
api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) {
|
||||
w.Header().Set("Allow", allowed)
|
||||
writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method."))
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server.New - generated server: %w", err)
|
||||
}
|
||||
return accessLog(generated, logger, recoverPanics(logger, limitBody(maxRequestBytes, generated))), nil
|
||||
}
|
||||
|
||||
// limitBody refuses bodies above the limit before they are read.
|
||||
func limitBody(limit int64, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.ContentLength > limit {
|
||||
writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit."))
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
// The panic value may hold request data; only its type is logged.
|
||||
logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered)))
|
||||
writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request."))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// accessLog writes one line per request with the operation, status, and
|
||||
// duration. Bodies, headers, and query strings are never logged.
|
||||
func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(recorder, r)
|
||||
operation := "unknown"
|
||||
if route, ok := router.FindPath(r.Method, r.URL); ok {
|
||||
operation = route.OperationID()
|
||||
}
|
||||
logger.InfoContext(r.Context(), "request",
|
||||
slog.String("method", r.Method),
|
||||
slog.String("operation", operation),
|
||||
slog.Int("status", recorder.status),
|
||||
slog.Int64("duration_ms", time.Since(started).Milliseconds()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/runner/internal/jobs"
|
||||
"lincodex/runner/internal/judge"
|
||||
)
|
||||
|
||||
const (
|
||||
testToken = "test-token-0123456789abcdefghijklmnop"
|
||||
// Markers that must never reach a log line.
|
||||
secretSource = "print('source-marker-7f3a')"
|
||||
secretInput = "input-marker-91c2"
|
||||
maxBody = 64 << 10
|
||||
)
|
||||
|
||||
// blockingRunner holds runs until release is closed.
|
||||
type blockingRunner struct {
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (r blockingRunner) Run(ctx context.Context, _ judge.Request) judge.Result {
|
||||
select {
|
||||
case <-r.release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
exit := 0
|
||||
return judge.Result{
|
||||
Outcome: judge.Accepted,
|
||||
Groups: []judge.GroupResult{{
|
||||
ID: "public", Visibility: judge.Public, Outcome: judge.Accepted, Passed: 1, Total: 1,
|
||||
MaxCPUTime: 25 * time.Millisecond, MaxMemoryKB: 9000,
|
||||
Tests: []judge.TestResult{{ID: "t1", Outcome: judge.Accepted, CPUTime: 25 * time.Millisecond, WallTime: 40 * time.Millisecond, MemoryKB: 9000, ExitCode: &exit}},
|
||||
}},
|
||||
Duration: 50 * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *syncBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *syncBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
type testServer struct {
|
||||
url string
|
||||
logs *syncBuffer
|
||||
// release lets every held run finish; it may be called more than once.
|
||||
release func()
|
||||
}
|
||||
|
||||
func startServer(t *testing.T) *testServer {
|
||||
t.Helper()
|
||||
logs := &syncBuffer{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
release := make(chan struct{})
|
||||
manager, err := jobs.NewManager(jobs.Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}, blockingRunner{release: release}, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
supports := func(language string) bool { return language == "python3" }
|
||||
handler := NewHandler(manager, supports, func() bool { return !manager.Draining() }, 3*time.Second, logger)
|
||||
httpHandler, err := New(handler, testToken, maxBody, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
server := httptest.NewServer(httpHandler)
|
||||
var releaseOnce sync.Once
|
||||
releaseRuns := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
t.Cleanup(func() {
|
||||
releaseRuns()
|
||||
server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_ = manager.Close(ctx)
|
||||
})
|
||||
return &testServer{url: server.URL, logs: logs, release: releaseRuns}
|
||||
}
|
||||
|
||||
func runBody(source string) map[string]any {
|
||||
return map[string]any{
|
||||
"language": "python3",
|
||||
"source": source,
|
||||
"limits": map[string]any{"time_limit_ms": 1000, "memory_limit_mb": 64, "output_limit_kb": 64},
|
||||
"groups": []any{map[string]any{
|
||||
"id": "public", "visibility": "public", "checker": map[string]any{"kind": "exact"},
|
||||
"tests": []any{map[string]any{"id": "t1", "input": secretInput, "expected_output": "3\n"}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
// reply is a response with its decoded JSON body; the body is already closed.
|
||||
type reply struct {
|
||||
StatusCode int
|
||||
Header http.Header
|
||||
}
|
||||
|
||||
func (s *testServer) do(t *testing.T, method, path, token string, body any) (reply, map[string]any) {
|
||||
t.Helper()
|
||||
var reader io.Reader = http.NoBody
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("encode body: %v", err)
|
||||
}
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
request, err := http.NewRequestWithContext(t.Context(), method, s.url+path, reader)
|
||||
if err != nil {
|
||||
t.Fatalf("new request: %v", err)
|
||||
}
|
||||
if body != nil {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var decoded map[string]any
|
||||
raw, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
t.Fatalf("decode %s: %v", raw, err)
|
||||
}
|
||||
}
|
||||
return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded
|
||||
}
|
||||
|
||||
func runPath(id uuid.UUID) string {
|
||||
return "/v1/runs/" + id.String()
|
||||
}
|
||||
|
||||
func TestRunOperationsRequireTheBearerToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := startServer(t)
|
||||
id := uuid.New()
|
||||
for _, token := range []string{"", "wrong-token-0123456789abcdefghijklmnop", testToken + "x"} {
|
||||
response, body := server.do(t, http.MethodPut, runPath(id), token, runBody(secretSource))
|
||||
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
|
||||
t.Fatalf("PUT with token %q = %d %v, want 401 unauthenticated", token, response.StatusCode, body)
|
||||
}
|
||||
response, _ = server.do(t, http.MethodGet, runPath(id), token, nil)
|
||||
if response.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("GET with token %q = %d, want 401", token, response.StatusCode)
|
||||
}
|
||||
}
|
||||
response, body := server.do(t, http.MethodGet, "/healthz", "", nil)
|
||||
if response.StatusCode != http.StatusOK || body["status"] != "ok" {
|
||||
t.Fatalf("healthz = %d %v", response.StatusCode, body)
|
||||
}
|
||||
response, body = server.do(t, http.MethodGet, "/readyz", "", nil)
|
||||
if response.StatusCode != http.StatusOK || body["status"] != "ready" {
|
||||
t.Fatalf("readyz = %d %v", response.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitRunIsIdempotentAndAnswersBusy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := startServer(t)
|
||||
id := uuid.New()
|
||||
response, body := server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource))
|
||||
if response.StatusCode != http.StatusAccepted || body["state"] != "running" || body["run_id"] != id.String() {
|
||||
t.Fatalf("first PUT = %d %v, want 202 running", response.StatusCode, body)
|
||||
}
|
||||
response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource))
|
||||
if response.StatusCode != http.StatusOK || body["state"] != "running" {
|
||||
t.Fatalf("repeated PUT = %d %v, want 200 running", response.StatusCode, body)
|
||||
}
|
||||
response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody("print(2)"))
|
||||
if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" {
|
||||
t.Fatalf("PUT with another payload = %d %v, want 422", response.StatusCode, body)
|
||||
}
|
||||
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, runBody(secretSource))
|
||||
if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "runner_busy" || response.Header.Get("Retry-After") != "3" {
|
||||
t.Fatalf("PUT while busy = %d %v %q, want 503 runner_busy with Retry-After 3", response.StatusCode, body, response.Header.Get("Retry-After"))
|
||||
}
|
||||
|
||||
server.release()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
response, body = server.do(t, http.MethodGet, runPath(id), testToken, nil)
|
||||
if body["state"] == "finished" || time.Now().After(deadline) {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
result, ok := body["result"].(map[string]any)
|
||||
if response.StatusCode != http.StatusOK || !ok || result["outcome"] != "accepted" {
|
||||
t.Fatalf("GET finished run = %d %v", response.StatusCode, body)
|
||||
}
|
||||
group := result["groups"].([]any)[0].(map[string]any)
|
||||
test := group["tests"].([]any)[0].(map[string]any)
|
||||
if group["passed_tests"] != float64(1) || test["time_ms"] != float64(25) || test["memory_kb"] != float64(9000) {
|
||||
t.Fatalf("group result = %v, want the recorded time and memory", group)
|
||||
}
|
||||
|
||||
logs := server.logs.String()
|
||||
if strings.Contains(logs, "source-marker") || strings.Contains(logs, secretInput) || strings.Contains(logs, testToken) {
|
||||
t.Fatalf("logs contain request data: %s", logs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitRunValidatesTheRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := startServer(t)
|
||||
duplicate := runBody(secretSource)
|
||||
group := duplicate["groups"].([]any)[0]
|
||||
duplicate["groups"] = []any{group, group}
|
||||
response, body := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, duplicate)
|
||||
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
|
||||
t.Fatalf("duplicate group IDs = %d %v, want 400", response.StatusCode, body)
|
||||
}
|
||||
pointer := body["errors"].([]any)[0].(map[string]any)["pointer"]
|
||||
if pointer != "/groups/1/id" {
|
||||
t.Fatalf("pointer = %v, want /groups/1/id", pointer)
|
||||
}
|
||||
|
||||
unknown := runBody(secretSource)
|
||||
unknown["candidate_id"] = "c-1"
|
||||
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, unknown)
|
||||
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
|
||||
t.Fatalf("unknown field = %d %v, want 400", response.StatusCode, body)
|
||||
}
|
||||
|
||||
tooLarge := runBody(strings.Repeat("x", maxBody))
|
||||
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, tooLarge)
|
||||
if response.StatusCode != http.StatusRequestEntityTooLarge || body["code"] != "payload_too_large" {
|
||||
t.Fatalf("large body = %d %v, want 413", response.StatusCode, body)
|
||||
}
|
||||
|
||||
response, body = server.do(t, http.MethodPut, "/v1/runs/not-a-uuid", testToken, runBody(secretSource))
|
||||
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
|
||||
t.Fatalf("invalid run ID = %d %v, want 400", response.StatusCode, body)
|
||||
}
|
||||
|
||||
response, body = server.do(t, http.MethodGet, runPath(uuid.New()), testToken, nil)
|
||||
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
|
||||
t.Fatalf("unknown run = %d %v, want 404", response.StatusCode, body)
|
||||
}
|
||||
response, body = server.do(t, http.MethodGet, "/v1/unknown", testToken, nil)
|
||||
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
|
||||
t.Fatalf("unknown route = %d %v, want 404", response.StatusCode, body)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user