package runner import ( "context" "encoding/json" "errors" "fmt" "log" "net/http" "os/exec" "regexp" "strings" "time" ) // maxBody caps a request. It also bounds every expected output, which // compareCap relies on. const maxBody = 2 << 20 // maxTests is the most tests one run may carry. const maxTests = 100 // server is the service behind Handler. type server struct { // slots holds one token per run or lint in progress, so at most // MAX_PARALLEL compilers and programs compete for the container's CPUs // and the timings stay meaningful. slots chan struct{} budget time.Duration } // Handler serves the runner's API: // // POST /run RunRequest -> RunResponse // POST /lint LintRequest -> LintResponse // GET /health 200 and which tools are installed // // A request the runner cannot take (an unknown lang, an io or file name // that is not a bare name, over 100 tests, a time limit over 10s) is 400, // or 413 when over 2 MB, and one that // could not get a slot within its budget is 503, all as {"error": "..."}. // A program that fails to compile is a 200: that is a result, not an error. func Handler(maxParallel int) http.Handler { return newServer(maxParallel, requestBudget).routes() } func newServer(maxParallel int, budget time.Duration) *server { if maxParallel < 1 { maxParallel = 1 } return &server{slots: make(chan struct{}, maxParallel), budget: budget} } func (s *server) routes() http.Handler { mux := http.NewServeMux() mux.HandleFunc("POST /run", s.handleRun) mux.HandleFunc("POST /lint", s.handleLint) mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"ok": true, "tools": Tools()}) }) return mux } // Tools reports which of the runner's programs are on PATH. Only g++ and // python3 are needed to run code; the linters are optional. func Tools() map[string]bool { tools := map[string]bool{} for _, bin := range []string{"g++", "python3", "clang-tidy", "ruff"} { _, err := exec.LookPath(bin) tools[bin] = err == nil } return tools } func (s *server) handleRun(w http.ResponseWriter, r *http.Request) { var req RunRequest if !decode(w, r, &req) { return } if err := validate(req.Lang, req.Files); err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } if req.IO != "" && !bareName.MatchString(req.IO) { writeError(w, http.StatusBadRequest, fmt.Sprintf("io %q is not a bare file name", req.IO)) return } if len(req.Tests) > maxTests { writeError(w, http.StatusBadRequest, fmt.Sprintf("%d tests: at most %d per run", len(req.Tests), maxTests)) return } if req.TimeLimitMs < 0 || req.TimeLimitMs > 10_000 { writeError(w, http.StatusBadRequest, "timeLimitMs must be between 0 and 10000") return } start := time.Now() resp, err := withSlot(s, r.Context(), w, func(ctx context.Context) (RunResponse, error) { return run(ctx, req) }) if err != nil { return } log.Printf("[run] %s, %d tests: %s in %dms", req.Lang, len(req.Tests), summary(resp), time.Since(start).Milliseconds()) writeJSON(w, http.StatusOK, resp) } func (s *server) handleLint(w http.ResponseWriter, r *http.Request) { var req LintRequest if !decode(w, r, &req) { return } if err := validate(req.Lang, req.Files); err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } resp, err := withSlot(s, r.Context(), w, func(ctx context.Context) (LintResponse, error) { return lint(ctx, req) }) if err != nil { return } writeJSON(w, http.StatusOK, resp) } // withSlot runs f once a slot is free, under the request's budget, which // starts on arrival so time spent queueing counts against it. On failure // it has already answered. func withSlot[T any](s *server, parent context.Context, w http.ResponseWriter, f func(context.Context) (T, error)) (T, error) { var zero T ctx, cancel := context.WithTimeout(parent, s.budget) defer cancel() select { case s.slots <- struct{}{}: case <-ctx.Done(): writeError(w, http.StatusServiceUnavailable, "the runner is busy: try again in a moment") return zero, ctx.Err() } defer func() { <-s.slots }() out, err := f(ctx) if err != nil { log.Printf("[runner] %v", err) writeError(w, http.StatusInternalServerError, err.Error()) return zero, err } return out, nil } // bareName is a file name with no directory part that cannot be "." or // "..", hidden, or an option to a tool. var bareName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) func validate(lang string, files map[string]string) error { if _, ok := languages[lang]; !ok { return fmt.Errorf("unknown lang %q (want %s or %s)", lang, Cpp, Python) } for name := range files { if !bareName.MatchString(name) || len(name) > 128 { return fmt.Errorf("file %q is not a bare file name", name) } if reserved[name] { return fmt.Errorf("file %q is the runner's own", name) } } return nil } func decode(w http.ResponseWriter, r *http.Request, v any) bool { err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody)).Decode(v) var tooBig *http.MaxBytesError switch { case errors.As(err, &tooBig): writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the request is over %d MB", maxBody>>20)) return false case err != nil: writeError(w, http.StatusBadRequest, "bad JSON: "+err.Error()) return false } return true } // summary is the log line's verdict count: "compile error", "3 AC, 1 WA". func summary(resp RunResponse) string { if !resp.Compile.OK { return "compile error" } counts := map[string]int{} for _, r := range resp.Results { counts[r.Verdict]++ } var parts []string for _, v := range []string{Accepted, WrongAnswer, RuntimeError, TimeLimit, Unchecked} { if counts[v] > 0 { parts = append(parts, fmt.Sprintf("%d %s", counts[v], v)) } } if len(parts) == 0 { return "compiled" } return strings.Join(parts, ", ") } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(v) } func writeError(w http.ResponseWriter, status int, msg string) { writeJSON(w, status, map[string]string{"error": msg}) }