Run and lint solutions on the site
A new admin-only solve page, /p/<name>/solve, edits a problem's code in
C++ or Python (a dropdown switches between them), runs it on custom
input or against the saved tests with per-test verdicts (AC, WA, RE,
TLE, unchecked) and compile errors, marks lint diagnostics in the
editor, and saves the code back as a commit ("Edit <name>"). Drafts
stay in the browser per problem and language until saved. LeetCode
problems are C++ only, since their tests run through driver.h.
Code never runs in the site, which holds the Claude, Gitea and S3
secrets. A separate runner service (cmd/usacorunner, Dockerfile.runner)
does it in a container meant to have no environment, an internal-only
network, a read-only root apart from /tmp, and memory, CPU and pids
limits, with tini to reap orphans. Runs copy the CLI: the same g++
flags with -DLOCAL and the repo's headers, <io>.in on disk and on
stdin, <io>.out or stdout as the output, and usaco test's comparison.
Unlike the CLI they have CPU, memory, file and wall-clock limits.
C++ lint is g++'s warnings plus clang-tidy with a new .clang-tidy
(bugprone, performance and a few readability checks; template.cpp is
clean). Python lint is a syntax check plus ruff. template.py is the
Python starter, with a stdio() helper like template.rs's.
CI builds, smoke-tests and rolls out the runner image before the site.
The web_server stack needs a usaco-runner service before that rollout
can succeed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
// Package handlers is the site's REST API: the problem list and pages (public
|
||||
// for solved problems, everything for the admin), the admin's edits, the
|
||||
// Claude explanations (explain.go) and recording reviews (review.go), and
|
||||
// the Gitea webhook that tells the server to pull.
|
||||
// Claude explanations (explain.go) and recording reviews (review.go), the
|
||||
// solve page's code editing and runs (run.go), and the Gitea webhook that
|
||||
// tells the server to pull.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
@@ -43,6 +44,9 @@ type Server struct {
|
||||
// Pull asks for a sync. It must not block: the webhook answers at once
|
||||
// and the sync runs in the background.
|
||||
Pull func()
|
||||
// Dir is the clone's work tree. The solve page reads solutions and tests
|
||||
// from it rather than the index, which truncates big files.
|
||||
Dir string
|
||||
// Claude writes the explanations; nil when CLAUDE_API_KEY is not set,
|
||||
// which turns only that feature off.
|
||||
Claude explain.Asker
|
||||
@@ -55,6 +59,9 @@ type Server struct {
|
||||
// Audio keeps review recordings for playback; nil when the S3_*
|
||||
// settings are not given, and the recordings are then thrown away.
|
||||
Audio AudioStore
|
||||
// Runner compiles, runs and lints code for the solve page; nil when
|
||||
// RUNNER_URL is not set, which turns only running and linting off.
|
||||
Runner Runner
|
||||
|
||||
idx atomic.Pointer[index.Index]
|
||||
// Separate, so a review and an explanation of one problem can run at
|
||||
@@ -97,6 +104,10 @@ func (s *Server) Routes(api *gin.RouterGroup) {
|
||||
admin.GET("/problems/:name/review", s.reviewStatus)
|
||||
admin.GET("/problems/:name/reviews/:id/audio", s.reviewAudio)
|
||||
admin.DELETE("/problems/:name/reviews/:id", s.deleteReview)
|
||||
admin.GET("/problems/:name/code", s.getCode)
|
||||
admin.PUT("/problems/:name/code", s.saveCode)
|
||||
admin.POST("/problems/:name/run", s.run)
|
||||
admin.POST("/problems/:name/lint", s.lint)
|
||||
api.POST("/hooks/gitea", s.webhook)
|
||||
}
|
||||
|
||||
@@ -202,15 +213,21 @@ func (e *requestError) Error() string { return e.msg }
|
||||
func (s *Server) mutate(ctx *gin.Context, name, message string, edit func(dir string) error) {
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
err := s.Repo.Mutate(c, message, edit)
|
||||
if err := s.Repo.Mutate(c, message, edit); err != nil {
|
||||
editFailed(ctx, message, err)
|
||||
return
|
||||
}
|
||||
if p, ok := s.Index().Problems[name]; ok {
|
||||
ctx.JSON(http.StatusOK, p)
|
||||
} else {
|
||||
ctx.JSON(http.StatusOK, gin.H{})
|
||||
}
|
||||
}
|
||||
|
||||
// editFailed answers for an edit Mutate refused or could not save.
|
||||
func editFailed(ctx *gin.Context, message string, err error) {
|
||||
var re *requestError
|
||||
switch {
|
||||
case err == nil:
|
||||
if p, ok := s.Index().Problems[name]; ok {
|
||||
ctx.JSON(http.StatusOK, p)
|
||||
} else {
|
||||
ctx.JSON(http.StatusOK, gin.H{})
|
||||
}
|
||||
case errors.As(err, &re):
|
||||
ctx.JSON(re.status, gin.H{"error": re.msg})
|
||||
case errors.Is(err, repo.ErrRejected):
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/runner"
|
||||
)
|
||||
|
||||
// Runner is the part of runner.Client the handlers use, so tests can fake
|
||||
// the runner service.
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, req runner.RunRequest) (runner.RunResponse, error)
|
||||
Lint(ctx context.Context, req runner.LintRequest) (runner.LintResponse, error)
|
||||
}
|
||||
|
||||
// Caps on what the solve page sends. The source cap is far above any real
|
||||
// solution; the body cap leaves room for a custom input beside it.
|
||||
const (
|
||||
maxSource = 256 << 10
|
||||
maxRunBody = 512 << 10
|
||||
maxRunTests = 16 << 20
|
||||
)
|
||||
|
||||
// The runner's own deadline is below the client's 90 seconds; these sit
|
||||
// between, so a slow run comes back as the runner's answer.
|
||||
const (
|
||||
runTimeout = 80 * time.Second
|
||||
lintTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// The repo root files a C++ build may include. The CLI builds with the root
|
||||
// on the include path and LOCAL defined, so a solution may include
|
||||
// debugging.h, and a LeetCode one leetcode.h and its driver.h; the runner
|
||||
// gets them all so the same source compiles there.
|
||||
var rootHeaders = []string{"debugging.h", "leetcode.h"}
|
||||
|
||||
// codeFile is one language's source on the solve page.
|
||||
type codeFile struct {
|
||||
Path string `json:"path"`
|
||||
Source string `json:"source"`
|
||||
// Saved is false for a starter, which exists only in the browser until
|
||||
// the admin saves it.
|
||||
Saved bool `json:"saved"`
|
||||
}
|
||||
|
||||
// layout is what the solve page needs to know about a problem dir. It is
|
||||
// read from the clone each time: the index truncates files, and a solution
|
||||
// saved here must come back in full.
|
||||
type layout struct {
|
||||
dir string
|
||||
io string
|
||||
leetcode bool
|
||||
cpp string // "main.cpp" when it exists
|
||||
python string // "main.py", else "sol.py", when one exists
|
||||
}
|
||||
|
||||
// readLayout looks at the problem's dir as the CLI would. Reads happen
|
||||
// outside the repo's lock, so a sync may be resetting the tree underneath;
|
||||
// at worst a request sees a file missing and the admin retries.
|
||||
func (s *Server) readLayout(status, name string) (*layout, error) {
|
||||
l := &layout{dir: filepath.Join(s.Dir, status, name)}
|
||||
entries, err := os.ReadDir(l.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
have := map[string]bool{}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
have[e.Name()] = true
|
||||
// The first *.in, as detect_io picks it.
|
||||
if base, ok := strings.CutSuffix(e.Name(), ".in"); ok && l.io == "" {
|
||||
l.io = base
|
||||
}
|
||||
}
|
||||
// With no sample, `usaco new` wires the source to the problem's name.
|
||||
if l.io == "" {
|
||||
l.io = name
|
||||
}
|
||||
l.leetcode = have["driver.h"]
|
||||
if have["main.cpp"] {
|
||||
l.cpp = "main.cpp"
|
||||
}
|
||||
switch {
|
||||
case have["main.py"]:
|
||||
l.python = "main.py"
|
||||
case have["sol.py"]:
|
||||
l.python = "sol.py"
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (l *layout) languages() []string {
|
||||
// A LeetCode problem's tests only run through its C++ driver.h.
|
||||
if l.leetcode {
|
||||
return []string{runner.Cpp}
|
||||
}
|
||||
return []string{runner.Cpp, runner.Python}
|
||||
}
|
||||
|
||||
func (l *layout) allows(lang string) bool {
|
||||
for _, x := range l.languages() {
|
||||
if x == lang {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// getCode is the solve page's starting point: each language's saved source,
|
||||
// or a starter wired to the problem's io name the way `usaco new` would.
|
||||
func (s *Server) getCode(ctx *gin.Context) {
|
||||
p, ok := s.lookup(ctx, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
l, err := s.readLayout(p.Status, p.Name)
|
||||
if err != nil {
|
||||
log.Printf("[code] %s: %v", p.Name, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
|
||||
return
|
||||
}
|
||||
def := runner.Cpp
|
||||
if l.cpp == "" && l.python != "" {
|
||||
def = runner.Python
|
||||
}
|
||||
code := map[string]codeFile{}
|
||||
for _, lang := range l.languages() {
|
||||
f, err := s.code(l, lang)
|
||||
if err != nil {
|
||||
var re *requestError
|
||||
if errors.As(err, &re) {
|
||||
ctx.JSON(re.status, gin.H{"error": re.msg})
|
||||
return
|
||||
}
|
||||
log.Printf("[code] %s: %v", p.Name, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
|
||||
return
|
||||
}
|
||||
code[lang] = f
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"io": l.io,
|
||||
"leetcode": l.leetcode,
|
||||
"languages": l.languages(),
|
||||
"default": def,
|
||||
"runner": s.Runner != nil,
|
||||
"code": code,
|
||||
})
|
||||
}
|
||||
|
||||
// code is one language's saved source, or its starter.
|
||||
func (s *Server) code(l *layout, lang string) (codeFile, error) {
|
||||
saved := l.cpp
|
||||
if lang == runner.Python {
|
||||
saved = l.python
|
||||
}
|
||||
if saved != "" {
|
||||
src, err := readCapped(filepath.Join(l.dir, saved), maxSource)
|
||||
if errors.Is(err, errTooBig) {
|
||||
return codeFile{}, &requestError{http.StatusUnprocessableEntity, saved + " is over 256 KB, too big to edit here"}
|
||||
}
|
||||
return codeFile{Path: saved, Source: src, Saved: true}, err
|
||||
}
|
||||
if lang == runner.Python {
|
||||
return codeFile{Path: "main.py", Source: s.pythonStarter(l.io)}, nil
|
||||
}
|
||||
return codeFile{Path: "main.cpp", Source: s.cppStarter(l.io)}, nil
|
||||
}
|
||||
|
||||
// Used only when the repo has no template, which it always should.
|
||||
const (
|
||||
fallbackCpp = "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n cin.tie(0)->sync_with_stdio(0);\n}\n"
|
||||
fallbackPy = "def main():\n n = int(input())\n print(n)\n\n\nmain()\n"
|
||||
)
|
||||
|
||||
// cppStarter is fresh_main's C++ case: template.cpp with the STDIO call
|
||||
// added as the first line of main. The io name is quoted rather than pasted
|
||||
// in as sed does, which is the same for every name the CLI makes.
|
||||
func (s *Server) cppStarter(io string) string {
|
||||
b, err := os.ReadFile(filepath.Join(s.Dir, "template.cpp"))
|
||||
if err != nil {
|
||||
return fallbackCpp
|
||||
}
|
||||
lines := strings.SplitAfter(string(b), "\n")
|
||||
for i, line := range lines {
|
||||
if strings.TrimSuffix(line, "\n") == "int main() {" {
|
||||
lines[i] = line + " STDIO(" + strconv.Quote(io) + ");\n"
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
// The call in main, indented, and not the stdio("name") in the comment
|
||||
// that explains it.
|
||||
var stdioCall = regexp.MustCompile(`(?m)^[ \t]+stdio\("[^"]*"\)`)
|
||||
|
||||
// pythonStarter is template.py with its stdio("...") call pointed at io, as
|
||||
// fresh_main does for template.rs.
|
||||
func (s *Server) pythonStarter(io string) string {
|
||||
b, err := os.ReadFile(filepath.Join(s.Dir, "template.py"))
|
||||
if err != nil {
|
||||
return fallbackPy
|
||||
}
|
||||
return stdioCall.ReplaceAllStringFunc(string(b), func(call string) string {
|
||||
indent := call[:strings.Index(call, "stdio(")]
|
||||
return indent + "stdio(" + strconv.Quote(io) + ")"
|
||||
})
|
||||
}
|
||||
|
||||
var errTooBig = errors.New("file too big")
|
||||
|
||||
// readCapped reads a whole file, refusing one over max rather than cutting
|
||||
// it: a cut solution saved back would lose its end.
|
||||
func readCapped(path string, max int64) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(f, max+1))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if int64(len(b)) > max {
|
||||
return "", errTooBig
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
type codeBody struct {
|
||||
Lang string `json:"lang"`
|
||||
Source string `json:"source"`
|
||||
// Mode and Input are for runs only.
|
||||
Mode string `json:"mode"`
|
||||
Input string `json:"input"`
|
||||
}
|
||||
|
||||
// readCode reads and checks a solve page request against the problem's
|
||||
// layout. It has answered when ok is false.
|
||||
func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) {
|
||||
p, ok := s.lookup(ctx, true)
|
||||
if !ok {
|
||||
return body, nil, false
|
||||
}
|
||||
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody)
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
var tooBig *http.MaxBytesError
|
||||
if errors.As(err, &tooBig) {
|
||||
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"})
|
||||
return body, nil, false
|
||||
}
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
||||
return body, nil, false
|
||||
}
|
||||
if len(body.Source) > maxSource {
|
||||
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"})
|
||||
return body, nil, false
|
||||
}
|
||||
if body.Lang != runner.Cpp && body.Lang != runner.Python {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"})
|
||||
return body, nil, false
|
||||
}
|
||||
l, err := s.readLayout(p.Status, p.Name)
|
||||
if err != nil {
|
||||
log.Printf("[code] %s: %v", p.Name, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
|
||||
return body, nil, false
|
||||
}
|
||||
if !l.allows(body.Lang) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"})
|
||||
return body, nil, false
|
||||
}
|
||||
return body, l, true
|
||||
}
|
||||
|
||||
// headers are the files written next to a C++ source; Python needs none.
|
||||
func (s *Server) headers(l *layout, lang string) (map[string]string, error) {
|
||||
if lang != runner.Cpp {
|
||||
return nil, nil
|
||||
}
|
||||
files := map[string]string{}
|
||||
add := func(path string) error {
|
||||
src, err := readCapped(path, maxSource)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files[filepath.Base(path)] = src
|
||||
return nil
|
||||
}
|
||||
for _, h := range rootHeaders {
|
||||
if err := add(filepath.Join(s.Dir, h)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if l.leetcode {
|
||||
if err := add(filepath.Join(l.dir, "driver.h")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// runnerConfigured answers 503 when there is no runner to ask.
|
||||
func (s *Server) runnerConfigured(ctx *gin.Context) bool {
|
||||
if s.Runner == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the code runner is not configured on this server (RUNNER_URL)"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// run compiles the source once and runs it on the saved tests or on one
|
||||
// custom input, and answers with the runner's verdicts as they are.
|
||||
func (s *Server) run(ctx *gin.Context) {
|
||||
if !s.runnerConfigured(ctx) {
|
||||
return
|
||||
}
|
||||
body, l, ok := s.readCode(ctx)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var tests []runner.Test
|
||||
switch body.Mode {
|
||||
case "tests":
|
||||
var err error
|
||||
if tests, err = readRunTests(l); err != nil {
|
||||
var re *requestError
|
||||
if errors.As(err, &re) {
|
||||
ctx.JSON(re.status, gin.H{"error": re.msg})
|
||||
return
|
||||
}
|
||||
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the tests could not be read"})
|
||||
return
|
||||
}
|
||||
case "custom":
|
||||
tests = []runner.Test{{Name: "custom", Input: body.Input}}
|
||||
default:
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "mode must be tests or custom"})
|
||||
return
|
||||
}
|
||||
files, err := s.headers(l, body.Lang)
|
||||
if err != nil {
|
||||
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the headers could not be read"})
|
||||
return
|
||||
}
|
||||
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), runTimeout)
|
||||
defer cancel()
|
||||
res, err := s.Runner.Run(c, runner.RunRequest{Lang: body.Lang, Source: body.Source, Files: files, IO: l.io, Tests: tests})
|
||||
if err != nil {
|
||||
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// readRunTests is what `usaco test` runs: tests/N.in, with N.out as the
|
||||
// expected output when it was saved, in sort -V order. A problem with no
|
||||
// tests runs its sample instead, unchecked: its <io>.out is the last run's
|
||||
// output, not an answer. Files are read whole, unlike the index's copies.
|
||||
func readRunTests(l *layout) ([]runner.Test, error) {
|
||||
tdir := filepath.Join(l.dir, "tests")
|
||||
entries, err := os.ReadDir(tdir)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
if base, ok := strings.CutSuffix(e.Name(), ".in"); ok && !e.IsDir() {
|
||||
names = append(names, base)
|
||||
}
|
||||
}
|
||||
sort.Slice(names, func(i, j int) bool { return naturalLess(names[i], names[j]) })
|
||||
|
||||
tests := []runner.Test{}
|
||||
total := 0
|
||||
read := func(path string) (string, error) {
|
||||
src, err := readCapped(path, maxRunTests)
|
||||
if errors.Is(err, errTooBig) || total+len(src) > maxRunTests {
|
||||
return "", &requestError{http.StatusRequestEntityTooLarge, "the saved tests are over 16 MB, too big to run from the site"}
|
||||
}
|
||||
total += len(src)
|
||||
return src, err
|
||||
}
|
||||
for _, name := range names {
|
||||
in, err := read(filepath.Join(tdir, name+".in"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := runner.Test{Name: name, Input: in}
|
||||
out, err := read(filepath.Join(tdir, name+".out"))
|
||||
switch {
|
||||
case err == nil:
|
||||
t.Output = &out
|
||||
case !os.IsNotExist(err):
|
||||
return nil, err
|
||||
}
|
||||
tests = append(tests, t)
|
||||
}
|
||||
if len(tests) > 0 {
|
||||
return tests, nil
|
||||
}
|
||||
sample, err := read(filepath.Join(l.dir, l.io+".in"))
|
||||
switch {
|
||||
case os.IsNotExist(err):
|
||||
// Nothing to run against: the runner still compiles, which is
|
||||
// worth seeing.
|
||||
return tests, nil
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case strings.TrimSpace(sample) == "":
|
||||
return tests, nil
|
||||
}
|
||||
return []runner.Test{{Name: "sample", Input: sample}}, nil
|
||||
}
|
||||
|
||||
// naturalLess orders like sort -V for test names: runs of digits compare as
|
||||
// numbers, so 2 comes before 10.
|
||||
func naturalLess(a, b string) bool {
|
||||
for a != "" && b != "" {
|
||||
da, db := digitRun(a), digitRun(b)
|
||||
if da > 0 && db > 0 {
|
||||
na, nb := strings.TrimLeft(a[:da], "0"), strings.TrimLeft(b[:db], "0")
|
||||
if len(na) != len(nb) {
|
||||
return len(na) < len(nb)
|
||||
}
|
||||
if na != nb {
|
||||
return na < nb
|
||||
}
|
||||
a, b = a[da:], b[db:]
|
||||
continue
|
||||
}
|
||||
if a[0] != b[0] {
|
||||
return a[0] < b[0]
|
||||
}
|
||||
a, b = a[1:], b[1:]
|
||||
}
|
||||
return len(a) < len(b)
|
||||
}
|
||||
|
||||
func digitRun(s string) int {
|
||||
n := 0
|
||||
for n < len(s) && s[n] >= '0' && s[n] <= '9' {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// lint returns the source's diagnostics, for the editor's squiggles.
|
||||
func (s *Server) lint(ctx *gin.Context) {
|
||||
if !s.runnerConfigured(ctx) {
|
||||
return
|
||||
}
|
||||
body, l, ok := s.readCode(ctx)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
files, err := s.headers(l, body.Lang)
|
||||
if err != nil {
|
||||
log.Printf("[lint] %s: %v", filepath.Base(l.dir), err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the headers could not be read"})
|
||||
return
|
||||
}
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), lintTimeout)
|
||||
defer cancel()
|
||||
res, err := s.Runner.Lint(c, runner.LintRequest{Lang: body.Lang, Source: body.Source, Files: files})
|
||||
if err != nil {
|
||||
log.Printf("[lint] %s: %v", filepath.Base(l.dir), err)
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// saveCode commits the editor's source as the problem's solution. An
|
||||
// unchanged source makes no commit: Mutate skips an empty diff.
|
||||
func (s *Server) saveCode(ctx *gin.Context) {
|
||||
body, _, ok := s.readCode(ctx)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(body.Source) == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
|
||||
return
|
||||
}
|
||||
src := body.Source
|
||||
if !strings.HasSuffix(src, "\n") {
|
||||
src += "\n"
|
||||
}
|
||||
name := ctx.Param("name")
|
||||
var saved string
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
err := s.Repo.Mutate(c, "Edit "+name, func(dir string) error {
|
||||
status, err := findOnDisk(dir, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pdir := filepath.Join(dir, status, name)
|
||||
// main.cpp is the CLI's; a Python solution keeps the sol.py some
|
||||
// older ones were written as, and is main.py otherwise.
|
||||
saved = "main.cpp"
|
||||
if body.Lang == runner.Python {
|
||||
saved = "main.py"
|
||||
if !exists(filepath.Join(pdir, "main.py")) && exists(filepath.Join(pdir, "sol.py")) {
|
||||
saved = "sol.py"
|
||||
}
|
||||
}
|
||||
return os.WriteFile(filepath.Join(pdir, saved), []byte(src), 0o644)
|
||||
})
|
||||
if err != nil {
|
||||
editFailed(ctx, "Edit "+name, err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"path": saved})
|
||||
}
|
||||
|
||||
func exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/runner"
|
||||
)
|
||||
|
||||
// fakeRunner records what the site asked for and answers with a fixed
|
||||
// result, or err.
|
||||
type fakeRunner struct {
|
||||
run *runner.RunRequest
|
||||
lint *runner.LintRequest
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeRunner) Run(_ context.Context, req runner.RunRequest) (runner.RunResponse, error) {
|
||||
f.run = &req
|
||||
if f.err != nil {
|
||||
return runner.RunResponse{}, f.err
|
||||
}
|
||||
return runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Name: "1", Verdict: runner.Accepted}}}, nil
|
||||
}
|
||||
|
||||
func (f *fakeRunner) Lint(_ context.Context, req runner.LintRequest) (runner.LintResponse, error) {
|
||||
f.lint = &req
|
||||
if f.err != nil {
|
||||
return runner.LintResponse{}, f.err
|
||||
}
|
||||
return runner.LintResponse{Diagnostics: []runner.Diagnostic{{Line: 1, Col: 1, Severity: "warning", Message: "x", Source: "g++"}}}, nil
|
||||
}
|
||||
|
||||
// setupRun adds the solve page's cases to setup's repo: moocast (solved,
|
||||
// C++, tests 1, 2 and 10 with one .out missing), cow-tipping (sol.py and a
|
||||
// sample only) and two-sum (LeetCode, with driver.h), plus the repo root's
|
||||
// templates and headers.
|
||||
func setupRun(t *testing.T) (*gin.Engine, *dirRepo, *fakeRunner) {
|
||||
t.Helper()
|
||||
r, repo, _ := setup(t)
|
||||
files := map[string]string{
|
||||
"template.cpp": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n FASTIO;\n}\n",
|
||||
"template.py": "# stdio(\"name\") opens name.in\ndef main():\n stdio(\"problem\")\n\n\nmain()\n",
|
||||
"debugging.h": "// debugging\n",
|
||||
"leetcode.h": "// leetcode\n",
|
||||
"solved/moocast/moocast.in": "3\n",
|
||||
"solved/moocast/tests/1.in": "1\n",
|
||||
"solved/moocast/tests/1.out": "one\n",
|
||||
"solved/moocast/tests/2.in": "2\n",
|
||||
"solved/moocast/tests/10.in": "10\n",
|
||||
"solved/moocast/tests/10.out": "ten\n",
|
||||
"solved/cow-tipping/cowtip.in": "2\n01\n10\n",
|
||||
"solved/cow-tipping/cowtip.out": "3\n",
|
||||
"solved/cow-tipping/sol.py": "print(1)\n",
|
||||
"solving/two-sum/main.cpp": "class Solution {};\n",
|
||||
"solving/two-sum/driver.h": "// driver\n",
|
||||
"solving/two-sum/two-sum.in": "[1,2]\n3\n",
|
||||
"solving/two-sum/tests/1.in": "[1,2]\n3\n",
|
||||
"solving/two-sum/tests/1.out": "[0,1]\n",
|
||||
"solving/watermelon/notes.md": "hm\n",
|
||||
"solving/watermelon/watermelon.in": "8\n",
|
||||
}
|
||||
for p, c := range files {
|
||||
os.MkdirAll(filepath.Join(repo.dir, filepath.Dir(p)), 0o755)
|
||||
os.WriteFile(filepath.Join(repo.dir, p), []byte(c), 0o644)
|
||||
}
|
||||
// watermelon is the C++ problem with no saved solution.
|
||||
os.Remove(filepath.Join(repo.dir, "solving/watermelon/main.cpp"))
|
||||
if err := repo.srv.Reload(repo.dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fr := &fakeRunner{}
|
||||
repo.srv.Dir, repo.srv.Runner = repo.dir, fr
|
||||
return r, repo, fr
|
||||
}
|
||||
|
||||
type codeReply struct {
|
||||
IO string `json:"io"`
|
||||
Leetcode bool `json:"leetcode"`
|
||||
Languages []string `json:"languages"`
|
||||
Default string `json:"default"`
|
||||
Runner bool `json:"runner"`
|
||||
Code map[string]codeFile `json:"code"`
|
||||
}
|
||||
|
||||
func getCodeReply(t *testing.T, r *gin.Engine, name string) codeReply {
|
||||
t.Helper()
|
||||
rec := do(r, "GET", "/usaco/api/problems/"+name+"/code", "", true)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("GET code of %s = %d %s", name, rec.Code, rec.Body)
|
||||
}
|
||||
var out codeReply
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestGetCode(t *testing.T) {
|
||||
r, _, _ := setupRun(t)
|
||||
|
||||
c := getCodeReply(t, r, "moocast")
|
||||
if c.IO != "moocast" || c.Leetcode || c.Default != "cpp" || !c.Runner || strings.Join(c.Languages, ",") != "cpp,python" {
|
||||
t.Fatalf("moocast = %+v", c)
|
||||
}
|
||||
if f := c.Code["cpp"]; f != (codeFile{Path: "main.cpp", Source: "int main() {}\n", Saved: true}) {
|
||||
t.Fatalf("moocast cpp = %+v, want the saved main.cpp", f)
|
||||
}
|
||||
if f := c.Code["python"]; f.Saved || f.Path != "main.py" || !strings.Contains(f.Source, " stdio(\"moocast\")\n") || !strings.Contains(f.Source, `# stdio("name")`) {
|
||||
t.Fatalf("moocast python = %+v, want the starter wired to moocast", f)
|
||||
}
|
||||
|
||||
c = getCodeReply(t, r, "cow-tipping")
|
||||
if c.IO != "cowtip" || c.Default != "python" {
|
||||
t.Fatalf("cow-tipping = %+v, want io cowtip and python by default", c)
|
||||
}
|
||||
if f := c.Code["python"]; f != (codeFile{Path: "sol.py", Source: "print(1)\n", Saved: true}) {
|
||||
t.Fatalf("cow-tipping python = %+v, want the saved sol.py", f)
|
||||
}
|
||||
|
||||
c = getCodeReply(t, r, "two-sum")
|
||||
if !c.Leetcode || strings.Join(c.Languages, ",") != "cpp" || c.Code["python"] != (codeFile{}) {
|
||||
t.Fatalf("two-sum = %+v, want a C++-only LeetCode problem", c)
|
||||
}
|
||||
|
||||
// The starter is fresh_main's: STDIO as main's first line.
|
||||
c = getCodeReply(t, r, "watermelon")
|
||||
want := "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n STDIO(\"watermelon\");\n FASTIO;\n}\n"
|
||||
if f := c.Code["cpp"]; f.Saved || f.Path != "main.cpp" || f.Source != want {
|
||||
t.Fatalf("watermelon cpp = %+v, want the wired template", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTests(t *testing.T) {
|
||||
r, _, fr := setupRun(t)
|
||||
rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"int main() {}","mode":"tests"}`, true)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"verdict":"AC"`) {
|
||||
t.Fatalf("run = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
req := fr.run
|
||||
if req.IO != "moocast" || req.Source != "int main() {}" || req.Lang != "cpp" {
|
||||
t.Fatalf("request = %+v", req)
|
||||
}
|
||||
var got []string
|
||||
for _, tc := range req.Tests {
|
||||
out := "-"
|
||||
if tc.Output != nil {
|
||||
out = *tc.Output
|
||||
}
|
||||
got = append(got, tc.Name+"="+strings.TrimSpace(tc.Input)+"/"+strings.TrimSpace(out))
|
||||
}
|
||||
if strings.Join(got, " ") != "1=1/one 2=2/- 10=10/ten" {
|
||||
t.Fatalf("tests = %v, want 1, 2, 10 in order with 2 unchecked", got)
|
||||
}
|
||||
if len(req.Files) != 2 || req.Files["debugging.h"] == "" || req.Files["leetcode.h"] == "" {
|
||||
t.Fatalf("files = %v, want the root headers", req.Files)
|
||||
}
|
||||
|
||||
// A LeetCode problem also gets its driver; Python gets nothing.
|
||||
do(r, "POST", "/usaco/api/problems/two-sum/run", `{"lang":"cpp","source":"x","mode":"tests"}`, true)
|
||||
if fr.run.Files["driver.h"] != "// driver\n" || len(fr.run.Files) != 3 {
|
||||
t.Fatalf("two-sum files = %v", fr.run.Files)
|
||||
}
|
||||
do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"python","source":"x","mode":"tests"}`, true)
|
||||
if len(fr.run.Files) != 0 {
|
||||
t.Fatalf("python files = %v, want none", fr.run.Files)
|
||||
}
|
||||
|
||||
// No tests dir: the sample, unchecked.
|
||||
do(r, "POST", "/usaco/api/problems/cow-tipping/run", `{"lang":"python","source":"x","mode":"tests"}`, true)
|
||||
if ts := fr.run.Tests; len(ts) != 1 || ts[0].Name != "sample" || ts[0].Output != nil || fr.run.IO != "cowtip" {
|
||||
t.Fatalf("cow-tipping tests = %+v", ts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCustomAndLint(t *testing.T) {
|
||||
r, _, fr := setupRun(t)
|
||||
rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"s","mode":"custom","input":"5 6\n"}`, true)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("custom run = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if ts := fr.run.Tests; len(ts) != 1 || ts[0].Name != "custom" || ts[0].Input != "5 6\n" || ts[0].Output != nil {
|
||||
t.Fatalf("custom tests = %+v", ts)
|
||||
}
|
||||
|
||||
rec = do(r, "POST", "/usaco/api/problems/moocast/lint", `{"lang":"cpp","source":"s"}`, true)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"diagnostics":[`) {
|
||||
t.Fatalf("lint = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if fr.lint.Source != "s" || fr.lint.Files["debugging.h"] == "" {
|
||||
t.Fatalf("lint request = %+v", fr.lint)
|
||||
}
|
||||
|
||||
fr.err = errors.New("runner: compiler exploded")
|
||||
if rec := do(r, "POST", "/usaco/api/problems/moocast/lint", `{"lang":"cpp","source":"s"}`, true); rec.Code != 502 || !strings.Contains(rec.Body.String(), "compiler exploded") {
|
||||
t.Fatalf("failed lint = %d %s, want 502 with the runner's message", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRefusals(t *testing.T) {
|
||||
r, repo, _ := setupRun(t)
|
||||
for _, c := range []struct{ path, body string }{
|
||||
{"moocast/run", `{"lang":"rust","source":"x","mode":"tests"}`},
|
||||
{"moocast/run", `{"lang":"cpp","source":"x","mode":"all"}`},
|
||||
{"two-sum/run", `{"lang":"python","source":"x","mode":"tests"}`},
|
||||
{"moocast/lint", `{"lang":"java","source":"x"}`},
|
||||
{"moocast/code", `{"lang":"cpp","source":" "}`},
|
||||
} {
|
||||
method := "POST"
|
||||
if strings.HasSuffix(c.path, "/code") {
|
||||
method = "PUT"
|
||||
}
|
||||
if rec := do(r, method, "/usaco/api/problems/"+c.path, c.body, true); rec.Code != 400 {
|
||||
t.Errorf("%s %s = %d %s, want 400", c.path, c.body, rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
for _, path := range []string{"code", "run", "lint"} {
|
||||
method := map[string]string{"code": "GET", "run": "POST", "lint": "POST"}[path]
|
||||
if rec := do(r, method, "/usaco/api/problems/moocast/"+path, `{"lang":"cpp","source":"x","mode":"tests"}`, false); rec.Code != 401 {
|
||||
t.Errorf("anonymous %s = %d, want 401", path, rec.Code)
|
||||
}
|
||||
}
|
||||
if rec := do(r, "PUT", "/usaco/api/problems/moocast/code", `{"lang":"cpp","source":"x"}`, false); rec.Code != 401 {
|
||||
t.Errorf("anonymous save = %d, want 401", rec.Code)
|
||||
}
|
||||
|
||||
repo.srv.Runner = nil
|
||||
if rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"x","mode":"tests"}`, true); rec.Code != 503 {
|
||||
t.Fatalf("run without a runner = %d, want 503", rec.Code)
|
||||
}
|
||||
if c := getCodeReply(t, r, "moocast"); c.Runner {
|
||||
t.Fatal("GET code says there is a runner when there is none")
|
||||
}
|
||||
if len(repo.msg) != 0 {
|
||||
t.Fatalf("refusals committed %v", repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveCode(t *testing.T) {
|
||||
r, repo, _ := setupRun(t)
|
||||
read := func(p string) string {
|
||||
b, _ := os.ReadFile(filepath.Join(repo.dir, p))
|
||||
return string(b)
|
||||
}
|
||||
|
||||
rec := do(r, "PUT", "/usaco/api/problems/moocast/code", `{"lang":"python","source":"print(2)"}`, true)
|
||||
if rec.Code != 200 || rec.Body.String() != `{"path":"main.py"}` {
|
||||
t.Fatalf("save python = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := read("solved/moocast/main.py"); got != "print(2)\n" {
|
||||
t.Fatalf("main.py = %q, want the source with a trailing newline", got)
|
||||
}
|
||||
if read("solved/moocast/main.cpp") == "" {
|
||||
t.Fatal("saving Python removed main.cpp")
|
||||
}
|
||||
|
||||
// An existing sol.py is kept as the Python file.
|
||||
rec = do(r, "PUT", "/usaco/api/problems/cow-tipping/code", `{"lang":"python","source":"print(3)\n"}`, true)
|
||||
if rec.Code != 200 || rec.Body.String() != `{"path":"sol.py"}` || read("solved/cow-tipping/sol.py") != "print(3)\n" {
|
||||
t.Fatalf("save sol.py = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(repo.dir, "solved/cow-tipping/main.py")); err == nil {
|
||||
t.Fatal("saving cow-tipping wrote main.py beside sol.py")
|
||||
}
|
||||
|
||||
rec = do(r, "PUT", "/usaco/api/problems/watermelon/code", `{"lang":"cpp","source":"int main() {}\n"}`, true)
|
||||
if rec.Code != 200 || rec.Body.String() != `{"path":"main.cpp"}` || read("solving/watermelon/main.cpp") != "int main() {}\n" {
|
||||
t.Fatalf("save cpp = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if strings.Join(repo.msg, ",") != "Edit moocast,Edit cow-tipping,Edit watermelon" {
|
||||
t.Fatalf("commit messages = %v", repo.msg)
|
||||
}
|
||||
// The saved source comes back as the page's code.
|
||||
if f := getCodeReply(t, r, "moocast").Code["python"]; f != (codeFile{Path: "main.py", Source: "print(2)\n", Saved: true}) {
|
||||
t.Fatalf("python after save = %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNaturalLess(t *testing.T) {
|
||||
in := []string{"10", "2", "1", "a10", "a2", "1a"}
|
||||
want := "1 1a 2 10 a2 a10"
|
||||
sorted := append([]string(nil), in...)
|
||||
for i := range sorted {
|
||||
for j := i + 1; j < len(sorted); j++ {
|
||||
if naturalLess(sorted[j], sorted[i]) {
|
||||
sorted[i], sorted[j] = sorted[j], sorted[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
if got := strings.Join(sorted, " "); got != want {
|
||||
t.Fatalf("sorted = %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# clang-tidy checks for this repo's competitive-programming C++.
|
||||
#
|
||||
# Kept byte-for-byte identical in two places, and a test in
|
||||
# site/internal/runner checks that they match:
|
||||
# .clang-tidy (repo root) for editors and clangd
|
||||
# site/internal/runner/clang-tidy.yaml embedded in the solve page's linter
|
||||
#
|
||||
# bugprone and performance catch real mistakes (int overflow before
|
||||
# widening, copies in hot loops, chained comparisons) without opinions on
|
||||
# style. Turned off are the checks that fire on the template itself or on
|
||||
# idioms that are normal in contest code:
|
||||
# macro-parentheses the template's F(i, L, R), takeI(n) etc.
|
||||
# easily-swappable-... every f(int a, int b)
|
||||
# narrowing-conversions int i = v.size() and friends, everywhere
|
||||
# switch-missing-default switches over a char read from input
|
||||
# avoid-endl interactive problems need the flush
|
||||
# enum-size an enum's base type never matters here
|
||||
# Compiler errors are left to g++, which the linter also runs.
|
||||
Checks: >-
|
||||
-*,
|
||||
bugprone-*,
|
||||
performance-*,
|
||||
readability-misleading-indentation,
|
||||
readability-redundant-*,
|
||||
-bugprone-easily-swappable-parameters,
|
||||
-bugprone-narrowing-conversions,
|
||||
-bugprone-macro-parentheses,
|
||||
-bugprone-switch-missing-default-case,
|
||||
-performance-avoid-endl,
|
||||
-performance-enum-size
|
||||
@@ -0,0 +1,74 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client is the site's side: it posts to the runner service at BaseURL.
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
// NewClient talks to the runner at baseURL (RUNNER_URL). The timeout is
|
||||
// above the service's own per-request deadline, so a slow run comes back as
|
||||
// the service's answer rather than a client timeout.
|
||||
func NewClient(baseURL string) *Client {
|
||||
return &Client{
|
||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||
HTTP: &http.Client{Timeout: 90 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// Run compiles req.Source once and runs it on every test.
|
||||
func (c *Client) Run(ctx context.Context, req RunRequest) (RunResponse, error) {
|
||||
var out RunResponse
|
||||
err := c.post(ctx, "/run", req, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Lint returns the source's diagnostics.
|
||||
func (c *Client) Lint(ctx context.Context, req LintRequest) (LintResponse, error) {
|
||||
var out LintResponse
|
||||
err := c.post(ctx, "/lint", req, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *Client) post(ctx context.Context, path string, in, out any) error {
|
||||
body, err := json.Marshal(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("runner: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
|
||||
if err != nil {
|
||||
return fmt.Errorf("runner: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// The service answers errors as {"error": "..."}, meant for the admin.
|
||||
var e struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(data, &e) == nil && e.Error != "" {
|
||||
return fmt.Errorf("runner: %s", e.Error)
|
||||
}
|
||||
return fmt.Errorf("runner: %s", resp.Status)
|
||||
}
|
||||
return json.Unmarshal(data, out)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func post(t *testing.T, h http.Handler, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
|
||||
func TestHandlerRejects(t *testing.T) {
|
||||
h := Handler(1)
|
||||
tooMany := `{"lang":"cpp","source":"","tests":[` + strings.TrimSuffix(strings.Repeat(`{"name":"x"},`, 101), ",") + `]}`
|
||||
for name, c := range map[string]struct {
|
||||
path, body string
|
||||
status int
|
||||
}{
|
||||
"lang": {"/run", `{"lang":"rust","source":""}`, 400},
|
||||
"io slash": {"/run", `{"lang":"cpp","source":"","io":"../x"}`, 400},
|
||||
"io dot": {"/run", `{"lang":"cpp","source":"","io":".hidden"}`, 400},
|
||||
"file slash": {"/run", `{"lang":"cpp","source":"","files":{"a/b.h":""}}`, 400},
|
||||
"file dotdot": {"/lint", `{"lang":"cpp","source":"","files":{"..":""}}`, 400},
|
||||
"reserved": {"/run", `{"lang":"cpp","source":"","files":{"main":""}}`, 400},
|
||||
"tests": {"/run", tooMany, 400},
|
||||
"json": {"/run", `{`, 400},
|
||||
"big": {"/run", `{"lang":"cpp","source":"` + strings.Repeat("x", maxBody) + `"}`, 413},
|
||||
} {
|
||||
w := post(t, h, c.path, c.body)
|
||||
var e struct{ Error string }
|
||||
json.Unmarshal(w.Body.Bytes(), &e)
|
||||
if w.Code != c.status || e.Error == "" {
|
||||
t.Errorf("%s: %d %s", name, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerRun(t *testing.T) {
|
||||
need(t, "g++")
|
||||
body := `{"lang":"cpp","source":` + jsonString(sumCpp) + `,"io":"sum","tests":[{"name":"1","input":"2 3","output":"5"}]}`
|
||||
w := post(t, Handler(1), "/run", body)
|
||||
var resp RunResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || w.Code != 200 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if !resp.Compile.OK || len(resp.Results) != 1 || resp.Results[0].Verdict != Accepted {
|
||||
t.Errorf("%+v", resp)
|
||||
}
|
||||
|
||||
// A compile error is still a 200.
|
||||
w = post(t, Handler(1), "/run", `{"lang":"cpp","source":"nope","tests":[]}`)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"ok":false`) {
|
||||
t.Errorf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerBusy(t *testing.T) {
|
||||
s := newServer(1, 50*time.Millisecond)
|
||||
s.slots <- struct{}{} // someone else's run
|
||||
w := post(t, s.routes(), "/lint", `{"lang":"cpp","source":""}`)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerHealth(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
Handler(1).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/health", nil))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"g++"`) {
|
||||
t.Errorf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAgainstHandler(t *testing.T) {
|
||||
need(t, "g++")
|
||||
ts := httptest.NewServer(Handler(1))
|
||||
defer ts.Close()
|
||||
c := NewClient(ts.URL)
|
||||
resp, err := c.Run(context.Background(), RunRequest{Lang: Cpp, Source: sumCpp, Tests: []Test{{Name: "1", Input: "1 1", Output: str("2")}}})
|
||||
if err != nil || len(resp.Results) != 1 || resp.Results[0].Verdict != Accepted {
|
||||
t.Errorf("%v %+v", err, resp)
|
||||
}
|
||||
if _, err := c.Lint(context.Background(), LintRequest{Lang: "go"}); err == nil || !strings.Contains(err.Error(), "unknown lang") {
|
||||
t.Errorf("err %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonString(s string) string {
|
||||
b, _ := json.Marshal(s)
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Limits on the submitted program, per test. The container adds its own
|
||||
// (memory, CPUs, pids) on top; these are what make one test fail on its own
|
||||
// instead of taking the service down with it.
|
||||
const (
|
||||
// memoryKB is RLIMIT_AS, the usual judge limit. It is address space, not
|
||||
// resident memory, so it also covers a vector that is reserved and never
|
||||
// touched. python3 starts in about 30 MB of it.
|
||||
memoryKB = 512 << 10
|
||||
// fileBlocks is RLIMIT_FSIZE in the shell's 512-byte blocks (64 MB). It
|
||||
// stops a runaway program filling the tmpfs; stdout and stderr go to
|
||||
// files, so it caps them too.
|
||||
fileBlocks = 64 << 20 / 512
|
||||
// compileMemoryKB is the build's address space. cc1plus needs around
|
||||
// 300 MB for <bits/stdc++.h> at -O2; this leaves room for heavier
|
||||
// templates while still stopping a template bomb before the container's
|
||||
// OOM killer picks a victim.
|
||||
compileMemoryKB = 1 << 20
|
||||
compileTimeout = 30 * time.Second
|
||||
lintTimeout = 20 * time.Second
|
||||
// requestBudget bounds a whole request, waiting for a slot included,
|
||||
// so the site's client (90s) always gets the service's answer.
|
||||
requestBudget = 60 * time.Second
|
||||
// compareCap is how much output is read back for comparing. A request
|
||||
// is at most 2 MB, so no expected output is longer: anything past this
|
||||
// is a wrong answer whatever it holds.
|
||||
compareCap = 4 << 20
|
||||
)
|
||||
|
||||
// limits are the rlimits one process runs under; zero leaves one unset.
|
||||
type limits struct {
|
||||
cpuSec int
|
||||
memoryKB int
|
||||
fileBlocks int
|
||||
}
|
||||
|
||||
// testLimits are a test's: the CPU limit rounded up to whole seconds (the
|
||||
// rlimit's unit) plus one, so the kernel only steps in for a program well
|
||||
// past the limit. The verdict itself compares the measured CPU time with
|
||||
// the exact limit.
|
||||
func testLimits(timeLimit time.Duration) limits {
|
||||
sec := int((timeLimit + time.Second - 1) / time.Second)
|
||||
return limits{cpuSec: sec + 1, memoryKB: memoryKB, fileBlocks: fileBlocks}
|
||||
}
|
||||
|
||||
// wallLimit is the clock time a test may take. It is well above the CPU
|
||||
// limit, because a loaded machine stretches wall time; it is what catches
|
||||
// a program that sleeps instead of computing.
|
||||
func wallLimit(timeLimit time.Duration) time.Duration {
|
||||
return 2*timeLimit + time.Second
|
||||
}
|
||||
|
||||
// script sets the rlimits and execs the program. The limits are set by a
|
||||
// shell rather than from Go because Go cannot set them on a child between
|
||||
// fork and exec without cgo, and setting them on the running child (prlimit
|
||||
// after Start) races with the program's first instructions. exec keeps the
|
||||
// shell out of the picture: the program is the process Go waits for, so
|
||||
// its exit status and rusage are the program's own.
|
||||
//
|
||||
// RLIMIT_NPROC is not set: it counts every process of the uid, which here
|
||||
// includes this server's own threads and every other run in flight, so any
|
||||
// value tight enough to stop a fork bomb would also fail unrelated runs.
|
||||
// The container's pids_limit bounds that instead: the process-group kill
|
||||
// below ends a fork bomb, and the image's init (tini) reaps what it leaves,
|
||||
// which this server, as PID 1, would not. The stack limit is raised to the memory
|
||||
// limit, as judges do for deep recursion; it is the one limit allowed to
|
||||
// fail, since some hosts cap the hard stack limit lower.
|
||||
func (l limits) script() string {
|
||||
var b strings.Builder
|
||||
// dash, bash-as-sh and busybox ash all take one resource per ulimit.
|
||||
var set []string
|
||||
if l.cpuSec > 0 {
|
||||
set = append(set, fmt.Sprintf("ulimit -t %d", l.cpuSec))
|
||||
}
|
||||
if l.memoryKB > 0 {
|
||||
set = append(set, fmt.Sprintf("ulimit -v %d", l.memoryKB))
|
||||
}
|
||||
if l.fileBlocks > 0 {
|
||||
set = append(set, fmt.Sprintf("ulimit -f %d", l.fileBlocks))
|
||||
}
|
||||
if len(set) > 0 {
|
||||
b.WriteString(strings.Join(set, " && "))
|
||||
b.WriteString(" || exit 126; ")
|
||||
}
|
||||
if l.memoryKB > 0 {
|
||||
fmt.Fprintf(&b, "ulimit -s %d 2>/dev/null; ", l.memoryKB)
|
||||
}
|
||||
b.WriteString(`exec "$@"`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// proc is one process to run.
|
||||
type proc struct {
|
||||
dir string
|
||||
args []string
|
||||
// stdin is a file to read from; empty means /dev/null.
|
||||
stdin string
|
||||
// stdout and stderr are files to write to; they may be the same.
|
||||
stdout, stderr string
|
||||
limits limits
|
||||
wall time.Duration
|
||||
}
|
||||
|
||||
// outcome is how a proc ended.
|
||||
type outcome struct {
|
||||
state *os.ProcessState // nil when it never started
|
||||
err error // why it never started
|
||||
wall time.Duration
|
||||
cpu time.Duration
|
||||
// timedOut is set when the proc's own wall limit killed it; stopped
|
||||
// when the caller's context did (the request's budget, or the client
|
||||
// going away).
|
||||
timedOut, stopped bool
|
||||
}
|
||||
|
||||
func (o outcome) signal() (syscall.Signal, bool) {
|
||||
if o.state == nil {
|
||||
return 0, false
|
||||
}
|
||||
ws, ok := o.state.Sys().(syscall.WaitStatus)
|
||||
if !ok || !ws.Signaled() {
|
||||
return 0, false
|
||||
}
|
||||
return ws.Signal(), true
|
||||
}
|
||||
|
||||
// exitCode is the exit status, or 128+signal as a shell reports a killed
|
||||
// program, or -1 when it never ran.
|
||||
func (o outcome) exitCode() int {
|
||||
if sig, ok := o.signal(); ok {
|
||||
return 128 + int(sig)
|
||||
}
|
||||
if o.state == nil {
|
||||
return -1
|
||||
}
|
||||
return o.state.ExitCode()
|
||||
}
|
||||
|
||||
// run runs p to completion, or until its wall limit or ctx ends it. The
|
||||
// process gets its own process group, and the whole group is killed both
|
||||
// on timeout and after it exits, so nothing it started outlives the test.
|
||||
func (p proc) run(ctx context.Context) outcome {
|
||||
tctx, cancel := context.WithTimeout(ctx, p.wall)
|
||||
defer cancel()
|
||||
|
||||
args := p.args
|
||||
if p.limits != (limits{}) {
|
||||
args = append([]string{"sh", "-c", p.limits.script(), "sh"}, args...)
|
||||
}
|
||||
cmd := exec.CommandContext(tctx, args[0], args[1:]...)
|
||||
cmd.Dir = p.dir
|
||||
cmd.Env = childEnv(p.dir)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
|
||||
|
||||
files, err := p.open(cmd)
|
||||
defer func() {
|
||||
for _, f := range files {
|
||||
f.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return outcome{err: err}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return outcome{err: err}
|
||||
}
|
||||
cmd.Wait() // the status is read from ProcessState below
|
||||
o := outcome{state: cmd.ProcessState, wall: time.Since(start)}
|
||||
// The group outlives its leader only if the program left children
|
||||
// behind; the pgid cannot be reused while they exist.
|
||||
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
o.cpu = o.state.UserTime() + o.state.SystemTime()
|
||||
if ctx.Err() != nil {
|
||||
o.stopped = true
|
||||
} else if errors.Is(tctx.Err(), context.DeadlineExceeded) {
|
||||
o.timedOut = true
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// open attaches p's files to cmd. Files rather than pipes: the program's
|
||||
// output then counts against RLIMIT_FSIZE, and Wait never waits on a pipe
|
||||
// held open by something the program left running.
|
||||
func (p proc) open(cmd *exec.Cmd) ([]*os.File, error) {
|
||||
var files []*os.File
|
||||
if p.stdin != "" {
|
||||
f, err := os.Open(p.stdin)
|
||||
if err != nil {
|
||||
return files, err
|
||||
}
|
||||
files = append(files, f)
|
||||
cmd.Stdin = f
|
||||
}
|
||||
out, err := os.Create(p.stdout)
|
||||
if err != nil {
|
||||
return files, err
|
||||
}
|
||||
files = append(files, out)
|
||||
cmd.Stdout = out
|
||||
cmd.Stderr = out
|
||||
if p.stderr != p.stdout {
|
||||
e, err := os.Create(p.stderr)
|
||||
if err != nil {
|
||||
return files, err
|
||||
}
|
||||
files = append(files, e)
|
||||
cmd.Stderr = e
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// childEnv is the whole environment a child sees: none of the server's.
|
||||
// LC_ALL=C keeps compiler messages in ASCII quotes, which the lint parsers
|
||||
// expect; python3 still switches itself to UTF-8 under it (PEP 538).
|
||||
func childEnv(dir string) []string {
|
||||
path := os.Getenv("PATH")
|
||||
if path == "" {
|
||||
path = "/usr/local/bin:/usr/bin:/bin"
|
||||
}
|
||||
return []string{
|
||||
"PATH=" + path,
|
||||
"HOME=" + dir,
|
||||
"TMPDIR=" + os.TempDir(),
|
||||
"LC_ALL=C",
|
||||
"PYTHONDONTWRITEBYTECODE=1",
|
||||
}
|
||||
}
|
||||
|
||||
// readCapped reads at most limit bytes of the file at path, and whether
|
||||
// there was more. A missing file reads as empty.
|
||||
func readCapped(path string, limit int) (string, bool) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
defer f.Close()
|
||||
data, _ := io.ReadAll(io.LimitReader(f, int64(limit)+1))
|
||||
if len(data) > limit {
|
||||
return string(data[:limit]), true
|
||||
}
|
||||
return string(data), false
|
||||
}
|
||||
|
||||
// capText cuts s to at most limit bytes without splitting a UTF-8
|
||||
// character, so the JSON carries no replacement characters for a cut.
|
||||
func capText(s string, limit int) (string, bool) {
|
||||
if len(s) <= limit {
|
||||
return s, false
|
||||
}
|
||||
s = s[:limit]
|
||||
for i := 0; i < utf8.UTFMax && len(s) > 0; i++ {
|
||||
r, size := utf8.DecodeLastRuneInString(s)
|
||||
if r != utf8.RuneError || size != 1 {
|
||||
break
|
||||
}
|
||||
s = s[:len(s)-1]
|
||||
}
|
||||
return s, true
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// tidyConfig is passed to clang-tidy with --config: the source is linted
|
||||
// in a temp directory outside the repo, so the repo's .clang-tidy (the
|
||||
// same file, for editors) is never found by clang-tidy's own search.
|
||||
//
|
||||
//go:embed clang-tidy.yaml
|
||||
var tidyConfig string
|
||||
|
||||
// ruffRules are ruff's defaults (pycodestyle errors, pyflakes) plus
|
||||
// bugbear, which catches the mutable-default and loop-variable mistakes
|
||||
// that bite in contest code. No style rules: the editor is not a formatter.
|
||||
const ruffRules = "E4,E7,E9,F,B"
|
||||
|
||||
// pySyntax reports the first syntax error as JSON. It runs isolated (-I),
|
||||
// so a submitted json.py cannot stand in for the real module, and calls
|
||||
// compile() rather than py_compile so it leaves no .pyc and gets the
|
||||
// error's span, not just a formatted traceback.
|
||||
const pySyntax = `import json
|
||||
try:
|
||||
compile(open("main.py", "rb").read(), "main.py", "exec")
|
||||
except SyntaxError as e:
|
||||
print(json.dumps({"line": e.lineno or 1, "col": e.offset or 0,
|
||||
"endLine": getattr(e, "end_lineno", 0) or 0, "endCol": getattr(e, "end_offset", 0) or 0,
|
||||
"msg": e.msg, "kind": type(e).__name__}))
|
||||
except ValueError as e:
|
||||
print(json.dumps({"line": 1, "col": 0, "msg": str(e), "kind": "ValueError"}))
|
||||
`
|
||||
|
||||
// tool is one linter: it runs in the workspace and returns diagnostics
|
||||
// already limited to the user's source.
|
||||
type tool struct {
|
||||
name string // as in Diagnostic.Source, and its binary on PATH
|
||||
bin string
|
||||
run func(ctx context.Context, ws *workspace) []Diagnostic
|
||||
}
|
||||
|
||||
var lintTools = map[string][]tool{
|
||||
Cpp: {{"g++", "g++", lintGCC}, {"clang-tidy", "clang-tidy", lintTidy}},
|
||||
Python: {{"python", "python3", lintPython}, {"ruff", "ruff", lintRuff}},
|
||||
}
|
||||
|
||||
// lint runs every linter for the language that is installed, at the same
|
||||
// time, and merges what they say. A missing tool is skipped: the solve
|
||||
// page lints less, it does not fail.
|
||||
func lint(ctx context.Context, req LintRequest) (LintResponse, error) {
|
||||
lang := languages[req.Lang]
|
||||
ws, err := newWorkspace(lang.source, req.Source, req.Files)
|
||||
if err != nil {
|
||||
return LintResponse{}, err
|
||||
}
|
||||
defer ws.remove()
|
||||
|
||||
tools := lintTools[req.Lang]
|
||||
found := make([][]Diagnostic, len(tools))
|
||||
var wg sync.WaitGroup
|
||||
for i, t := range tools {
|
||||
if _, err := exec.LookPath(t.bin); err != nil {
|
||||
continue
|
||||
}
|
||||
wg.Go(func() { found[i] = t.run(ctx, ws) })
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// python3 is the authority on syntax: ruff's own syntax errors say the
|
||||
// same thing at the same place, so they go when python3 has run.
|
||||
if req.Lang == Python && found[0] != nil {
|
||||
var kept []Diagnostic
|
||||
for _, d := range found[1] {
|
||||
if d.Rule != "" {
|
||||
kept = append(kept, d)
|
||||
}
|
||||
}
|
||||
found[1] = kept
|
||||
}
|
||||
|
||||
resp := LintResponse{Diagnostics: []Diagnostic{}}
|
||||
seen := map[string]bool{}
|
||||
for _, ds := range found {
|
||||
for _, d := range ds {
|
||||
key := strconv.Itoa(d.Line) + "\x00" + d.Message
|
||||
if !seen[key] {
|
||||
seen[key] = true
|
||||
resp.Diagnostics = append(resp.Diagnostics, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(resp.Diagnostics, func(i, j int) bool {
|
||||
a, b := resp.Diagnostics[i], resp.Diagnostics[j]
|
||||
if a.Line != b.Line {
|
||||
return a.Line < b.Line
|
||||
}
|
||||
return a.Col < b.Col
|
||||
})
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// runTool runs a linter in the workspace and returns its stdout and
|
||||
// stderr together. Linters get only the wall limit: what they parse is the
|
||||
// user's code, but they never run it.
|
||||
func runTool(ctx context.Context, ws *workspace, name string, args []string, stdin string) string {
|
||||
out := ws.capture(name + ".txt")
|
||||
o := proc{dir: ws.work, args: args, stdin: stdin, stdout: out, stderr: out, wall: lintTimeout}.run(ctx)
|
||||
if o.err != nil || o.timedOut {
|
||||
log.Printf("[lint] %s: err=%v timedOut=%v", name, o.err, o.timedOut)
|
||||
}
|
||||
text, _ := readCapped(out, compareCap)
|
||||
return text
|
||||
}
|
||||
|
||||
// C++
|
||||
|
||||
// lintGCC asks g++ for its warnings with the build's flags. Plain text,
|
||||
// not GCC's JSON: GCC 16 dropped -fdiagnostics-format=json for SARIF,
|
||||
// while the image's GCC 14 has both, and the one-line-per-diagnostic text
|
||||
// is the same on every version. Byte columns, so a tab counts as one
|
||||
// column as it does in the editor.
|
||||
func lintGCC(ctx context.Context, ws *workspace) []Diagnostic {
|
||||
out := runTool(ctx, ws, "g++", []string{
|
||||
"g++", "-fsyntax-only", "-fdiagnostics-plain-output", "-fdiagnostics-column-unit=byte",
|
||||
"-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "main.cpp",
|
||||
}, "")
|
||||
return parseGCC(out)
|
||||
}
|
||||
|
||||
var (
|
||||
// main.cpp:3:20: warning: unused variable 'x' [-Wunused-variable]
|
||||
diagLine = regexp.MustCompile(`^(.+?):(\d+):(\d+): (fatal error|error|warning|note): (.*)$`)
|
||||
// main.cpp:8:12: required from here
|
||||
requiredFrom = regexp.MustCompile(`^main\.cpp:(\d+):(\d+):\s+required from`)
|
||||
trailingRule = regexp.MustCompile(`^(.*) \[([^\[\]]+)\]$`)
|
||||
)
|
||||
|
||||
// parseGCC keeps main.cpp's diagnostics. An error inside a header that
|
||||
// main.cpp's code caused (std::sort on ints) is reported where GCC says
|
||||
// the instantiation came from in main.cpp, once per place, since a single
|
||||
// bad call can set off a page of header errors.
|
||||
func parseGCC(out string) []Diagnostic {
|
||||
var ds []Diagnostic
|
||||
var from []int // the last "main.cpp:L:C: required from" seen
|
||||
blamed := map[[2]int]bool{}
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if m := requiredFrom.FindStringSubmatch(line); m != nil {
|
||||
from = []int{atoi(m[1]), atoi(m[2])}
|
||||
continue
|
||||
}
|
||||
m := diagLine.FindStringSubmatch(line)
|
||||
if m == nil || m[4] == "note" {
|
||||
continue
|
||||
}
|
||||
msg, rule := splitRule(m[5])
|
||||
rule = strings.TrimSuffix(strings.TrimPrefix(rule, "-W"), "=")
|
||||
if rule == "enabled by default" {
|
||||
rule = ""
|
||||
}
|
||||
d := Diagnostic{Line: atoi(m[2]), Col: atoi(m[3]), Severity: severity(m[4]), Message: msg, Source: "g++", Rule: rule}
|
||||
if m[1] != "main.cpp" {
|
||||
if d.Severity != "error" || from == nil || blamed[[2]int{from[0], from[1]}] {
|
||||
continue
|
||||
}
|
||||
blamed[[2]int{from[0], from[1]}] = true
|
||||
d.Line, d.Col = from[0], from[1]
|
||||
d.Message += " (in " + filepath.Base(m[1]) + ")"
|
||||
}
|
||||
from = nil
|
||||
ds = append(ds, d)
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
// lintTidy runs clang-tidy with the embedded checks. clang-tidy only
|
||||
// reports on the main file unless told otherwise, so headers are quiet.
|
||||
func lintTidy(ctx context.Context, ws *workspace) []Diagnostic {
|
||||
out := runTool(ctx, ws, "clang-tidy", []string{
|
||||
"clang-tidy", "main.cpp", "--quiet", "--config=" + tidyConfig,
|
||||
"--", "-std=c++17", "-DLOCAL", "-I.",
|
||||
}, "")
|
||||
main := filepath.Join(ws.work, "main.cpp")
|
||||
paths := map[string]bool{"main.cpp": true, main: true}
|
||||
if real, err := filepath.EvalSymlinks(main); err == nil {
|
||||
paths[real] = true
|
||||
}
|
||||
return parseTidy(out, paths)
|
||||
}
|
||||
|
||||
// parseTidy keeps clang-tidy's own checks in the given file. Its
|
||||
// clang-diagnostic-* entries are clang's compiler errors, which g++ has
|
||||
// already reported in its own words.
|
||||
func parseTidy(out string, mainPaths map[string]bool) []Diagnostic {
|
||||
var ds []Diagnostic
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
m := diagLine.FindStringSubmatch(line)
|
||||
if m == nil || m[4] == "note" || !mainPaths[m[1]] {
|
||||
continue
|
||||
}
|
||||
msg, rule := splitRule(m[5])
|
||||
if rule == "" || strings.HasPrefix(rule, "clang-diagnostic-") {
|
||||
continue
|
||||
}
|
||||
ds = append(ds, Diagnostic{Line: atoi(m[2]), Col: atoi(m[3]), Severity: severity(m[4]), Message: msg, Source: "clang-tidy", Rule: rule})
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
// Python
|
||||
|
||||
func lintPython(ctx context.Context, ws *workspace) []Diagnostic {
|
||||
out := runTool(ctx, ws, "python", []string{"python3", "-I", "-c", pySyntax}, "")
|
||||
ds := parsePySyntax(out)
|
||||
if ds == nil {
|
||||
ds = []Diagnostic{} // ran and found nothing, which lint tells from not running
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
func parsePySyntax(out string) []Diagnostic {
|
||||
var e struct {
|
||||
Line, Col, EndLine, EndCol int
|
||||
Msg, Kind string
|
||||
}
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) != nil || e.Msg == "" {
|
||||
return nil
|
||||
}
|
||||
d := Diagnostic{Line: e.Line, Col: e.Col, Severity: "error", Message: e.Msg, Source: "python", Rule: e.Kind}
|
||||
if e.EndLine >= e.Line && e.EndCol > 0 {
|
||||
d.EndLine, d.EndCol = e.EndLine, e.EndCol
|
||||
}
|
||||
return []Diagnostic{d}
|
||||
}
|
||||
|
||||
// lintRuff passes the source on stdin, --isolated so no config file found
|
||||
// above the temp directory changes the rules.
|
||||
func lintRuff(ctx context.Context, ws *workspace) []Diagnostic {
|
||||
out := runTool(ctx, ws, "ruff", []string{
|
||||
"ruff", "check", "--isolated", "--no-cache", "--output-format=json",
|
||||
"--select", ruffRules, "--stdin-filename", "main.py", "-",
|
||||
}, filepath.Join(ws.work, "main.py"))
|
||||
ds, err := parseRuff(out)
|
||||
if err != nil {
|
||||
log.Printf("[lint] ruff: %v", err)
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
func parseRuff(out string) ([]Diagnostic, error) {
|
||||
var items []struct {
|
||||
Code *string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Location struct {
|
||||
Row, Column int
|
||||
} `json:"location"`
|
||||
End struct {
|
||||
Row, Column int
|
||||
} `json:"end_location"`
|
||||
}
|
||||
// Anything ruff prints besides the array (a warning) comes first.
|
||||
if i := strings.Index(out, "["); i > 0 {
|
||||
out = out[i:]
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ds []Diagnostic
|
||||
for _, it := range items {
|
||||
d := Diagnostic{
|
||||
Line: it.Location.Row, Col: it.Location.Column,
|
||||
EndLine: it.End.Row, EndCol: it.End.Column,
|
||||
Severity: "warning", Message: it.Message, Source: "ruff",
|
||||
}
|
||||
if it.Code != nil {
|
||||
d.Rule = *it.Code
|
||||
}
|
||||
// A syntax error, or a name that will raise NameError when run.
|
||||
if d.Rule == "" || strings.HasPrefix(d.Rule, "E9") || d.Rule == "F821" || d.Rule == "F822" || d.Rule == "F823" {
|
||||
d.Severity = "error"
|
||||
}
|
||||
ds = append(ds, d)
|
||||
}
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
func splitRule(msg string) (string, string) {
|
||||
if m := trailingRule.FindStringSubmatch(msg); m != nil {
|
||||
return m[1], m[2]
|
||||
}
|
||||
return msg, ""
|
||||
}
|
||||
|
||||
func severity(kind string) string {
|
||||
if strings.Contains(kind, "error") {
|
||||
return "error"
|
||||
}
|
||||
return "warning"
|
||||
}
|
||||
|
||||
func atoi(s string) int {
|
||||
n, _ := strconv.Atoi(s)
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func has(ds []Diagnostic, source, rule string, line int) bool {
|
||||
for _, d := range ds {
|
||||
if d.Source == source && d.Rule == rule && d.Line == line {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestLintCpp(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
src := "#include <vector>\nint main() {\n\tint unused;\n\tstd::vector<int> v;\n\tfor (int i = 0; i < v.size(); i++) {}\n}\n"
|
||||
resp, err := lint(context.Background(), LintRequest{Lang: Cpp, Source: src})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(resp.Diagnostics, "g++", "unused-variable", 3) || !has(resp.Diagnostics, "g++", "sign-compare", 5) {
|
||||
t.Fatalf("%+v", resp.Diagnostics)
|
||||
}
|
||||
for _, d := range resp.Diagnostics {
|
||||
// byte columns: the tab is one column, so "unused" starts at 6
|
||||
if d.Rule == "unused-variable" && d.Col != 6 {
|
||||
t.Errorf("column %d", d.Col)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintClangTidy(t *testing.T) {
|
||||
need(t, "g++", "clang-tidy")
|
||||
t.Parallel()
|
||||
src := "#include <vector>\nint f(int a, int b, int c) { return a == b == c; }\nint main() { return f(1, 2, 3); }\n"
|
||||
resp, err := lint(context.Background(), LintRequest{Lang: Cpp, Source: src})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(resp.Diagnostics, "clang-tidy", "bugprone-chained-comparison", 2) {
|
||||
t.Errorf("%+v", resp.Diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
// The template must lint clean, or every new problem starts with warnings
|
||||
// on lines its author never wrote.
|
||||
func TestLintTemplateClean(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
root := filepath.Join("..", "..", "..")
|
||||
tmpl, err := os.ReadFile(filepath.Join(root, "template.cpp"))
|
||||
if err != nil {
|
||||
t.Skip("not in the full repo: ", err) // CI exports site/ only
|
||||
}
|
||||
dbg, err := os.ReadFile(filepath.Join(root, "debugging.h"))
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
resp, err := lint(context.Background(), LintRequest{Lang: Cpp, Source: string(tmpl), Files: map[string]string{"debugging.h": string(dbg)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, d := range resp.Diagnostics {
|
||||
// The template's empty loop leaves t unused-but-set; that is the
|
||||
// author's to fill in, and only g++ may say so.
|
||||
if d.Source != "g++" {
|
||||
t.Errorf("template.cpp:%d:%d: %s [%s %s]", d.Line, d.Col, d.Message, d.Source, d.Rule)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClangTidyConfigMatchesRepo(t *testing.T) {
|
||||
repo, err := os.ReadFile(filepath.Join("..", "..", "..", ".clang-tidy"))
|
||||
if err != nil {
|
||||
t.Skip("not in the full repo: ", err)
|
||||
}
|
||||
if !bytes.Equal(repo, []byte(tidyConfig)) {
|
||||
t.Error(".clang-tidy and internal/runner/clang-tidy.yaml differ: keep them identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGCC(t *testing.T) {
|
||||
out := `main.cpp: In function 'int main()':
|
||||
main.cpp:3:7: warning: unused variable 'x' [-Wunused-variable]
|
||||
main.cpp:4:3: error: 'undeclared' was not declared in this scope
|
||||
main.cpp:4:3: note: suggested alternative: 'unsigned'
|
||||
In file included from /usr/include/c++/14/algorithm:61,
|
||||
from main.cpp:1:
|
||||
/usr/include/c++/14/bits/stl_algo.h: In instantiation of 'void std::sort(_RAIter, _RAIter) [with _RAIter = int]':
|
||||
main.cpp:8:12: required from here
|
||||
/usr/include/c++/14/bits/stl_algo.h:1817:9: error: no type named 'difference_type'
|
||||
/usr/include/c++/14/bits/stl_algo.h: In instantiation of 'void std::__heap_select(...)':
|
||||
/usr/include/c++/14/bits/stl_algo.h:4817:18: required from 'void std::sort(_RAIter, _RAIter) [with _RAIter = int]'
|
||||
main.cpp:8:12: required from here
|
||||
/usr/include/c++/14/bits/stl_algo.h:1595:20: error: invalid type argument of unary '*'
|
||||
debugging.h:2:1: warning: something in a header [-Wextra]
|
||||
`
|
||||
ds := parseGCC(out)
|
||||
want := []Diagnostic{
|
||||
{Line: 3, Col: 7, Severity: "warning", Message: "unused variable 'x'", Source: "g++", Rule: "unused-variable"},
|
||||
{Line: 4, Col: 3, Severity: "error", Message: "'undeclared' was not declared in this scope", Source: "g++"},
|
||||
{Line: 8, Col: 12, Severity: "error", Message: "no type named 'difference_type' (in stl_algo.h)", Source: "g++"},
|
||||
}
|
||||
if len(ds) != len(want) {
|
||||
t.Fatalf("got %+v", ds)
|
||||
}
|
||||
for i := range want {
|
||||
if ds[i] != want[i] {
|
||||
t.Errorf("%d: got %+v, want %+v", i, ds[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTidy(t *testing.T) {
|
||||
out := `/tmp/w/main.cpp:2:37: warning: chained comparison 'v0 == v1 == v2' may generate unintended results [bugprone-chained-comparison]
|
||||
2 | int f(int a, int b, int c) { return a == b == c; }
|
||||
| ^
|
||||
/tmp/w/main.cpp:5:1: error: use of undeclared identifier 'x' [clang-diagnostic-error]
|
||||
/tmp/w/driver.h:1:1: warning: in a header [bugprone-foo]
|
||||
/tmp/w/main.cpp:6:1: note: expanded from macro 'F'
|
||||
`
|
||||
ds := parseTidy(out, map[string]bool{"/tmp/w/main.cpp": true})
|
||||
if len(ds) != 1 || ds[0].Rule != "bugprone-chained-comparison" || ds[0].Line != 2 || ds[0].Col != 37 {
|
||||
t.Errorf("%+v", ds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintPython(t *testing.T) {
|
||||
need(t, "python3")
|
||||
t.Parallel()
|
||||
resp, err := lint(context.Background(), LintRequest{Lang: Python, Source: "def f(:\n pass\n"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ds := resp.Diagnostics
|
||||
if len(ds) != 1 || ds[0].Source != "python" || ds[0].Line != 1 || ds[0].Severity != "error" {
|
||||
t.Errorf("%+v", ds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintRuff(t *testing.T) {
|
||||
need(t, "python3", "ruff")
|
||||
t.Parallel()
|
||||
resp, err := lint(context.Background(), LintRequest{Lang: Python, Source: "import os\nprint(y)\n"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(resp.Diagnostics, "ruff", "F401", 1) || !has(resp.Diagnostics, "ruff", "F821", 2) {
|
||||
t.Errorf("%+v", resp.Diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
// A trimmed sample of ruff 0.11's --output-format=json, from Alpine 3.22.
|
||||
const ruffSample = `[
|
||||
{"cell": null, "code": "F401", "end_location": {"column": 10, "row": 1}, "filename": "/tmp/main.py",
|
||||
"fix": {"applicability": "safe", "edits": [], "message": "Remove unused import: ` + "`os`" + `"},
|
||||
"location": {"column": 8, "row": 1}, "message": "` + "`os`" + ` imported but unused", "noqa_row": 1,
|
||||
"url": "https://docs.astral.sh/ruff/rules/unused-import"},
|
||||
{"cell": null, "code": "F821", "end_location": {"column": 13, "row": 3}, "filename": "/tmp/main.py", "fix": null,
|
||||
"location": {"column": 12, "row": 3}, "message": "Undefined name ` + "`y`" + `", "noqa_row": 3, "url": null},
|
||||
{"cell": null, "code": null, "end_location": {"column": 8, "row": 5}, "filename": "/tmp/main.py", "fix": null,
|
||||
"location": {"column": 7, "row": 5}, "message": "SyntaxError: Expected a parameter", "noqa_row": null, "url": null}
|
||||
]`
|
||||
|
||||
func TestParseRuff(t *testing.T) {
|
||||
ds, err := parseRuff(ruffSample)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []Diagnostic{
|
||||
{Line: 1, Col: 8, EndLine: 1, EndCol: 10, Severity: "warning", Message: "`os` imported but unused", Source: "ruff", Rule: "F401"},
|
||||
{Line: 3, Col: 12, EndLine: 3, EndCol: 13, Severity: "error", Message: "Undefined name `y`", Source: "ruff", Rule: "F821"},
|
||||
{Line: 5, Col: 7, EndLine: 5, EndCol: 8, Severity: "error", Message: "SyntaxError: Expected a parameter", Source: "ruff"},
|
||||
}
|
||||
if len(ds) != len(want) {
|
||||
t.Fatalf("got %+v", ds)
|
||||
}
|
||||
for i := range want {
|
||||
if ds[i] != want[i] {
|
||||
t.Errorf("%d: got %+v, want %+v", i, ds[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePySyntax(t *testing.T) {
|
||||
ds := parsePySyntax(`{"line": 1, "col": 7, "endLine": 1, "endCol": 8, "msg": "invalid syntax", "kind": "SyntaxError"}` + "\n")
|
||||
if len(ds) != 1 || ds[0].Col != 7 || ds[0].EndCol != 8 || ds[0].Rule != "SyntaxError" {
|
||||
t.Errorf("%+v", ds)
|
||||
}
|
||||
if parsePySyntax("") != nil {
|
||||
t.Error("no output is no diagnostic")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// language is how one Lang is built and run, in the work directory.
|
||||
type language struct {
|
||||
source string
|
||||
// compile builds the program. For python it is only a syntax check, so
|
||||
// a SyntaxError is a failed build as it would be in C++, not a crash on
|
||||
// every test.
|
||||
compile []string
|
||||
run []string
|
||||
}
|
||||
|
||||
var languages = map[string]language{
|
||||
// The CLI's CXXFLAGS (lib/common.sh), with -I. for the repo root: the
|
||||
// request's Files hold debugging.h and leetcode.h.
|
||||
Cpp: {
|
||||
source: "main.cpp",
|
||||
compile: []string{"g++", "-O2", "-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "-o", "main", "main.cpp"},
|
||||
run: []string{"./main"},
|
||||
},
|
||||
// -I keeps a submitted py_compile.py from standing in for the real one.
|
||||
Python: {
|
||||
source: "main.py",
|
||||
compile: []string{"python3", "-I", "-m", "py_compile", "main.py"},
|
||||
run: []string{"python3", "main.py"},
|
||||
},
|
||||
}
|
||||
|
||||
// reserved are names the runner itself writes, so Files may not use them.
|
||||
var reserved = map[string]bool{"main.cpp": true, "main.py": true, "main": true}
|
||||
|
||||
// workspace is one request's temporary directory. The program runs in
|
||||
// work/; what the runner captures lives beside it, out of the program's way.
|
||||
type workspace struct {
|
||||
root, work string
|
||||
}
|
||||
|
||||
func newWorkspace(src, source string, files map[string]string) (*workspace, error) {
|
||||
// os.MkdirTemp honours TMPDIR, /tmp by default: in the container that
|
||||
// is the one writable (tmpfs) mount, and it must allow exec, since the
|
||||
// compiled program runs from it.
|
||||
root, err := os.MkdirTemp("", "usacorun-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ws := &workspace{root: root, work: filepath.Join(root, "work")}
|
||||
if err := os.Mkdir(ws.work, 0o755); err != nil {
|
||||
ws.remove()
|
||||
return nil, err
|
||||
}
|
||||
for name, body := range files {
|
||||
if err := os.WriteFile(filepath.Join(ws.work, name), []byte(body), 0o644); err != nil {
|
||||
ws.remove()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(ws.work, src), []byte(source), 0o644); err != nil {
|
||||
ws.remove()
|
||||
return nil, err
|
||||
}
|
||||
return ws, nil
|
||||
}
|
||||
|
||||
func (ws *workspace) remove() { os.RemoveAll(ws.root) }
|
||||
func (ws *workspace) capture(n string) string { return filepath.Join(ws.root, n) }
|
||||
|
||||
// run builds req.Source once and runs it on each test in order, in the
|
||||
// same directory, as `usaco test` does. The error is only for the runner
|
||||
// failing (no temp directory); anything wrong with the program is in the
|
||||
// response.
|
||||
func run(ctx context.Context, req RunRequest) (RunResponse, error) {
|
||||
lang := languages[req.Lang]
|
||||
ws, err := newWorkspace(lang.source, req.Source, req.Files)
|
||||
if err != nil {
|
||||
return RunResponse{}, err
|
||||
}
|
||||
defer ws.remove()
|
||||
|
||||
resp := RunResponse{Results: []Result{}}
|
||||
resp.Compile = compile(ctx, ws, lang)
|
||||
if !resp.Compile.OK {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
limit := time.Duration(req.TimeLimitMs) * time.Millisecond
|
||||
if limit <= 0 {
|
||||
limit = DefaultTimeLimitMs * time.Millisecond
|
||||
}
|
||||
for _, t := range req.Tests {
|
||||
resp.Results = append(resp.Results, runTest(ctx, ws, lang, ioName(req.IO), limit, t))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ioName is the file-IO name a request means. A problem with no io name
|
||||
// is a stdin/stdout one, which never opens the file, so any fixed name
|
||||
// does; "input" reads sensibly in a program's error messages.
|
||||
func ioName(io string) string {
|
||||
if io == "" {
|
||||
return "input"
|
||||
}
|
||||
return io
|
||||
}
|
||||
|
||||
func compile(ctx context.Context, ws *workspace, lang language) Compile {
|
||||
out := ws.capture("compile.txt")
|
||||
o := proc{
|
||||
dir: ws.work,
|
||||
args: lang.compile,
|
||||
stdout: out,
|
||||
stderr: out,
|
||||
limits: limits{cpuSec: int(compileTimeout / time.Second), memoryKB: compileMemoryKB, fileBlocks: fileBlocks},
|
||||
wall: compileTimeout,
|
||||
}.run(ctx)
|
||||
text, cut := readCapped(out, MaxOutput)
|
||||
text, _ = capText(text, MaxOutput)
|
||||
if cut {
|
||||
text += "\n[output cut]"
|
||||
}
|
||||
c := Compile{Output: text, TimeMs: o.wall.Milliseconds()}
|
||||
switch {
|
||||
case o.err != nil:
|
||||
c.Output = fmt.Sprintf("%s could not start on the runner: %v", lang.compile[0], o.err)
|
||||
case o.stopped:
|
||||
c.Output = strings.TrimSpace(text + "\n" + budgetMessage)
|
||||
case o.timedOut:
|
||||
c.Output = strings.TrimSpace(fmt.Sprintf("%s\ncompilation took longer than %s", text, compileTimeout))
|
||||
default:
|
||||
c.OK = o.state.Success()
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
const budgetMessage = "stopped: the request's 60s budget ran out"
|
||||
|
||||
// runTest runs one test the way lib/common.sh's run_solution does: in the
|
||||
// work directory with <io>.in on stdin, its output being <io>.out if it
|
||||
// wrote one and stdout otherwise.
|
||||
func runTest(ctx context.Context, ws *workspace, lang language, io string, limit time.Duration, t Test) Result {
|
||||
res := Result{Name: t.Name, Expected: t.Output}
|
||||
res.Input, res.Truncated = capText(t.Input, MaxOutput)
|
||||
if ctx.Err() != nil {
|
||||
res.Verdict, res.Message = TimeLimit, "not run: the request's 60s budget ran out"
|
||||
return res
|
||||
}
|
||||
|
||||
in := filepath.Join(ws.work, io+".in")
|
||||
outFile := filepath.Join(ws.work, io+".out")
|
||||
if err := os.WriteFile(in, []byte(t.Input), 0o644); err != nil {
|
||||
res.Verdict, res.Message = RuntimeError, "could not write "+io+".in: "+err.Error()
|
||||
return res
|
||||
}
|
||||
os.Remove(outFile)
|
||||
stdout, stderr := ws.capture("stdout"), ws.capture("stderr")
|
||||
o := proc{
|
||||
dir: ws.work,
|
||||
args: lang.run,
|
||||
stdin: in,
|
||||
stdout: stdout,
|
||||
stderr: stderr,
|
||||
limits: testLimits(limit),
|
||||
wall: wallLimit(limit),
|
||||
}.run(ctx)
|
||||
|
||||
res.TimeMs = o.wall.Milliseconds()
|
||||
res.ExitCode = o.exitCode()
|
||||
var cut bool
|
||||
res.Stderr, cut = readCapped(stderr, MaxStderr)
|
||||
res.Stderr, _ = capText(res.Stderr, MaxStderr)
|
||||
res.Truncated = res.Truncated || cut
|
||||
|
||||
// Only a regular file counts as the program's <io>.out; anything else
|
||||
// it left there (a directory, a symlink out of the sandbox) is ignored.
|
||||
from := stdout
|
||||
if fi, err := os.Lstat(outFile); err == nil && fi.Mode().IsRegular() {
|
||||
from = outFile
|
||||
}
|
||||
output, tooLong := readCapped(from, compareCap)
|
||||
res.Output, cut = capText(output, MaxOutput)
|
||||
res.Truncated = res.Truncated || cut
|
||||
|
||||
sig, signaled := o.signal()
|
||||
switch {
|
||||
case o.err != nil:
|
||||
res.Verdict, res.Message = RuntimeError, "could not start: "+o.err.Error()
|
||||
case o.stopped:
|
||||
res.Verdict, res.Message = TimeLimit, budgetMessage
|
||||
case o.timedOut:
|
||||
res.Verdict = TimeLimit
|
||||
res.Message = fmt.Sprintf("ran past the %s wall-clock limit (%s of CPU time)", seconds(wallLimit(limit)), seconds(o.cpu))
|
||||
// The rlimit is only a backstop a second above the limit: the verdict
|
||||
// is the measured CPU time against the exact one, as a judge's is.
|
||||
case signaled && sig == syscall.SIGXCPU, o.cpu > limit:
|
||||
res.Verdict = TimeLimit
|
||||
res.Message = fmt.Sprintf("used %s of CPU time; the limit is %s", seconds(o.cpu), seconds(limit))
|
||||
case signaled:
|
||||
res.Verdict = RuntimeError
|
||||
res.Message = fmt.Sprintf("killed by signal %d (%s)", int(sig), sig) + memoryHint(res.Stderr)
|
||||
case !o.state.Success():
|
||||
res.Verdict = RuntimeError
|
||||
res.Message = fmt.Sprintf("exit status %d", o.state.ExitCode()) + memoryHint(res.Stderr)
|
||||
case t.Output == nil:
|
||||
res.Verdict = Unchecked
|
||||
case tooLong:
|
||||
res.Verdict = WrongAnswer
|
||||
res.Message = fmt.Sprintf("the output is over %d MB", compareCap>>20)
|
||||
case normalize(output) == normalize(*t.Output):
|
||||
res.Verdict = Accepted
|
||||
default:
|
||||
res.Verdict = WrongAnswer
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// memoryHint names the likely cause when the program ran out of address
|
||||
// space: C++ aborts with bad_alloc, python raises MemoryError, and neither
|
||||
// says there was a limit.
|
||||
func memoryHint(stderr string) string {
|
||||
if strings.Contains(stderr, "bad_alloc") || strings.Contains(stderr, "MemoryError") {
|
||||
return fmt.Sprintf("; out of memory? The limit is %d MB", memoryKB>>10)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// normalize is test.sh's norm(): trailing whitespace off every line, then
|
||||
// trailing blank lines dropped, so a missing final newline or a stray
|
||||
// space never fails a test.
|
||||
func normalize(s string) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
for i, l := range lines {
|
||||
lines[i] = strings.TrimRight(l, " \t\r\v\f")
|
||||
}
|
||||
for len(lines) > 0 && lines[len(lines)-1] == "" {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// seconds formats a duration the way the messages quote limits: "2s",
|
||||
// "1.5s", "0.23s".
|
||||
func seconds(d time.Duration) string {
|
||||
s := fmt.Sprintf("%.2f", d.Seconds())
|
||||
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
|
||||
return s + "s"
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func need(t *testing.T, bins ...string) {
|
||||
t.Helper()
|
||||
for _, b := range bins {
|
||||
if _, err := exec.LookPath(b); err != nil {
|
||||
t.Skipf("%s is not installed", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func str(s string) *string { return &s }
|
||||
|
||||
func runOK(t *testing.T, req RunRequest) RunResponse {
|
||||
t.Helper()
|
||||
resp, err := run(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !resp.Compile.OK {
|
||||
t.Fatalf("compile failed:\n%s", resp.Compile.Output)
|
||||
}
|
||||
if len(resp.Results) != len(req.Tests) {
|
||||
t.Fatalf("%d results for %d tests", len(resp.Results), len(req.Tests))
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func verdict(t *testing.T, r Result, want string) {
|
||||
t.Helper()
|
||||
if r.Verdict != want {
|
||||
t.Errorf("%s: verdict %s (%s), want %s; output %q, stderr %q", r.Name, r.Verdict, r.Message, want, r.Output, r.Stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A sum over stdin, small headers so the compile is quick.
|
||||
const sumCpp = `#include <iostream>
|
||||
int main() { long long a, b; std::cin >> a >> b; std::cout << a + b << "\n"; }
|
||||
`
|
||||
|
||||
func TestCppVerdicts(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: sumCpp, IO: "sum", Tests: []Test{
|
||||
{Name: "ac", Input: "1 2\n", Output: str("3\n")},
|
||||
{Name: "wa", Input: "1 2\n", Output: str("4\n")},
|
||||
// norm(): trailing spaces and blank lines, and a missing newline, are ignored
|
||||
{Name: "norm", Input: "2 2", Output: str("4 \n\n\n")},
|
||||
{Name: "unchecked", Input: "5 5\n"},
|
||||
}})
|
||||
verdict(t, resp.Results[0], Accepted)
|
||||
verdict(t, resp.Results[1], WrongAnswer)
|
||||
verdict(t, resp.Results[2], Accepted)
|
||||
verdict(t, resp.Results[3], Unchecked)
|
||||
if got := resp.Results[3].Output; got != "10\n" {
|
||||
t.Errorf("unchecked output %q", got)
|
||||
}
|
||||
if resp.Results[0].Input != "1 2\n" || *resp.Results[1].Expected != "4\n" {
|
||||
t.Errorf("input/expected not echoed: %+v", resp.Results[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCppFileIO(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
// Writes its answer to <io>.out, as USACO's STDIO does, and something
|
||||
// else to stdout, which must then be ignored.
|
||||
src := `#include <cstdio>
|
||||
int main() {
|
||||
std::puts("noise");
|
||||
std::freopen("paint.in", "r", stdin);
|
||||
std::freopen("paint.out", "w", stdout);
|
||||
int a; std::scanf("%d", &a); std::printf("%d\n", a * 2);
|
||||
}
|
||||
`
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, IO: "paint", Tests: []Test{
|
||||
{Name: "1", Input: "21\n", Output: str("42\n")},
|
||||
{Name: "2", Input: "5\n", Output: str("10\n")},
|
||||
}})
|
||||
verdict(t, resp.Results[0], Accepted)
|
||||
verdict(t, resp.Results[1], Accepted)
|
||||
}
|
||||
|
||||
func TestCppCrashes(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
src := `#include <cstdio>
|
||||
#include <cstdlib>
|
||||
int main() {
|
||||
int k; std::scanf("%d", &k);
|
||||
if (k == 1) { volatile int *p = nullptr; *p = 1; }
|
||||
if (k == 2) { std::fprintf(stderr, "bad\n"); return 3; }
|
||||
std::puts("ok");
|
||||
}
|
||||
`
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, Tests: []Test{
|
||||
{Name: "segv", Input: "1"},
|
||||
{Name: "exit", Input: "2"},
|
||||
}})
|
||||
segv, exit := resp.Results[0], resp.Results[1]
|
||||
verdict(t, segv, RuntimeError)
|
||||
if !strings.Contains(segv.Message, "signal 11") || segv.ExitCode != 139 {
|
||||
t.Errorf("segv: %q, exit %d", segv.Message, segv.ExitCode)
|
||||
}
|
||||
verdict(t, exit, RuntimeError)
|
||||
if exit.Message != "exit status 3" || exit.ExitCode != 3 || exit.Stderr != "bad\n" {
|
||||
t.Errorf("exit: %+v", exit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCppTimeLimit(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
src := `int main() { volatile unsigned long x = 0; for (;;) x++; }`
|
||||
start := time.Now()
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, TimeLimitMs: 200, Tests: []Test{{Name: "loop", Output: str("")}}})
|
||||
verdict(t, resp.Results[0], TimeLimit)
|
||||
if resp.Results[0].Message == "" {
|
||||
t.Error("TLE without a message")
|
||||
}
|
||||
if d := time.Since(start); d > 10*time.Second {
|
||||
t.Errorf("took %s", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCppMeasuredCPUOverLimit(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
// Finishes on its own, after the 100ms limit: TLE by measurement, the
|
||||
// rlimit being a second above it.
|
||||
src := `#include <ctime>
|
||||
int main() { std::clock_t s = std::clock(); while (std::clock() - s < CLOCKS_PER_SEC / 2) {} }`
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, TimeLimitMs: 100, Tests: []Test{{Name: "slow"}}})
|
||||
verdict(t, resp.Results[0], TimeLimit)
|
||||
if !strings.Contains(resp.Results[0].Message, "CPU time") {
|
||||
t.Errorf("message %q", resp.Results[0].Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBudget(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
|
||||
defer cancel()
|
||||
src := `int main() { volatile unsigned long x = 0; for (;;) x++; }`
|
||||
// Each test may take 2*2s+1s; the budget runs out during the first.
|
||||
resp, err := run(ctx, RunRequest{Lang: Cpp, Source: src, Tests: []Test{{Name: "1"}, {Name: "2"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !resp.Compile.OK {
|
||||
t.Skipf("compile did not finish inside the budget:\n%s", resp.Compile.Output)
|
||||
}
|
||||
verdict(t, resp.Results[0], TimeLimit)
|
||||
verdict(t, resp.Results[1], TimeLimit)
|
||||
if resp.Results[0].Message != budgetMessage || !strings.HasPrefix(resp.Results[1].Message, "not run") {
|
||||
t.Errorf("messages %q, %q", resp.Results[0].Message, resp.Results[1].Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCppCompileError(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
resp, err := run(context.Background(), RunRequest{Lang: Cpp, Source: "int main() { return x; }", Tests: []Test{{Name: "1"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Compile.OK || !strings.Contains(resp.Compile.Output, "main.cpp:1") || len(resp.Results) != 0 {
|
||||
t.Errorf("%+v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCppFilesAndTemplate(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
// The LeetCode layout: a class in main.cpp, and a driver.h beside it
|
||||
// (from Files) that holds main(), included only in LOCAL builds.
|
||||
src := `#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
class Solution { public: int twice(int x) { return 2 * x; } };
|
||||
#ifdef LOCAL
|
||||
#include "driver.h"
|
||||
#endif
|
||||
`
|
||||
driver := `int main() {
|
||||
freopen("twice.in", "r", stdin);
|
||||
freopen("twice.out", "w", stdout);
|
||||
for (int x; cin >> x;) cout << Solution().twice(x) << '\n';
|
||||
}
|
||||
`
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, IO: "twice", Files: map[string]string{"driver.h": driver},
|
||||
Tests: []Test{{Name: "1", Input: "1\n2\n", Output: str("2\n4\n")}}})
|
||||
verdict(t, resp.Results[0], Accepted)
|
||||
}
|
||||
|
||||
func TestOutputCap(t *testing.T) {
|
||||
need(t, "g++")
|
||||
t.Parallel()
|
||||
src := `#include <cstdio>
|
||||
int main() { for (int i = 0; i < 200000; i++) std::puts("x"); }`
|
||||
resp := runOK(t, RunRequest{Lang: Cpp, Source: src, Tests: []Test{{Name: "big", Output: str("x\n")}}})
|
||||
r := resp.Results[0]
|
||||
verdict(t, r, WrongAnswer)
|
||||
if !r.Truncated || len(r.Output) != MaxOutput {
|
||||
t.Errorf("truncated %v, %d bytes", r.Truncated, len(r.Output))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPython(t *testing.T) {
|
||||
need(t, "python3")
|
||||
t.Parallel()
|
||||
resp := runOK(t, RunRequest{Lang: Python, Source: "a, b = map(int, input().split())\nprint(a + b)\n", Tests: []Test{
|
||||
{Name: "ac", Input: "1 2\n", Output: str("3")},
|
||||
{Name: "wa", Input: "1 2\n", Output: str("4")},
|
||||
{Name: "re", Input: "x\n", Output: str("4")},
|
||||
}})
|
||||
verdict(t, resp.Results[0], Accepted)
|
||||
verdict(t, resp.Results[1], WrongAnswer)
|
||||
verdict(t, resp.Results[2], RuntimeError)
|
||||
if !strings.Contains(resp.Results[2].Stderr, "ValueError") {
|
||||
t.Errorf("stderr %q", resp.Results[2].Stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPythonSyntaxError(t *testing.T) {
|
||||
need(t, "python3")
|
||||
t.Parallel()
|
||||
resp, err := run(context.Background(), RunRequest{Lang: Python, Source: "def f(:\n pass\n", Tests: []Test{{Name: "1"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Compile.OK || !strings.Contains(resp.Compile.Output, "SyntaxError") {
|
||||
t.Errorf("%+v", resp.Compile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"a \nb\t\n\n\n": "a\nb",
|
||||
"a\r\nb": "a\nb",
|
||||
"\n\na": "\n\na",
|
||||
"a\n\nb\n": "a\n\nb",
|
||||
"": "",
|
||||
" \n \n": "",
|
||||
} {
|
||||
if got := normalize(in); got != want {
|
||||
t.Errorf("normalize(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapText(t *testing.T) {
|
||||
s, cut := capText("aé", 2) // é is two bytes: cutting at 2 would split it
|
||||
if s != "a" || !cut {
|
||||
t.Errorf("%q %v", s, cut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitsScript(t *testing.T) {
|
||||
got := testLimits(1500 * time.Millisecond).script()
|
||||
want := `ulimit -t 3 && ulimit -v 524288 && ulimit -f 131072 || exit 126; ulimit -s 524288 2>/dev/null; exec "$@"`
|
||||
if got != want {
|
||||
t.Errorf("got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Package runner compiles and runs a solution against tests, and lints it,
|
||||
// for the site's solve page. The site never runs code itself: it holds the
|
||||
// Claude, Gitea and S3 secrets and shares a network with the rest of the
|
||||
// stack, so this runs as its own service (cmd/usacorunner) in a container
|
||||
// with no secrets, no outside network and hard resource limits. These types
|
||||
// are the JSON the site (Client) and the service (Handler) exchange.
|
||||
//
|
||||
// Running copies the CLI (lib/common.sh, lib/cmd/test.sh): the same g++
|
||||
// flags, the program runs in a directory holding <io>.in with that file also
|
||||
// on stdin, its output is <io>.out if it wrote one and stdout otherwise, and
|
||||
// outputs are compared with trailing whitespace and trailing blank lines
|
||||
// stripped.
|
||||
package runner
|
||||
|
||||
// Languages the runner knows, as the site's index names them
|
||||
// (index.File.Lang).
|
||||
const (
|
||||
Cpp = "cpp"
|
||||
Python = "python"
|
||||
)
|
||||
|
||||
// Verdicts, one per test.
|
||||
const (
|
||||
Accepted = "AC"
|
||||
WrongAnswer = "WA"
|
||||
RuntimeError = "RE"
|
||||
TimeLimit = "TLE"
|
||||
// Unchecked is a test with no expected output: it ran without crashing,
|
||||
// and its output is only shown.
|
||||
Unchecked = "unchecked"
|
||||
)
|
||||
|
||||
// RunRequest is POST /run.
|
||||
type RunRequest struct {
|
||||
Lang string `json:"lang"`
|
||||
Source string `json:"source"`
|
||||
// Files are written next to the source before compiling: driver.h from
|
||||
// a LeetCode problem's directory, and the repo root's debugging.h and
|
||||
// leetcode.h, which LOCAL builds include. Keys are bare file names.
|
||||
Files map[string]string `json:"files,omitempty"`
|
||||
// IO is the problem's file-IO name: each test's input is written to
|
||||
// <IO>.in, and <IO>.out is read back if the program wrote it.
|
||||
IO string `json:"io"`
|
||||
Tests []Test `json:"tests"`
|
||||
// TimeLimitMs is per test; zero means DefaultTimeLimitMs.
|
||||
TimeLimitMs int `json:"timeLimitMs,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultTimeLimitMs is the per-test CPU limit when the request gives none.
|
||||
const DefaultTimeLimitMs = 2000
|
||||
|
||||
// Test is one case. A nil Output means no expected output was saved.
|
||||
type Test struct {
|
||||
Name string `json:"name"`
|
||||
Input string `json:"input"`
|
||||
Output *string `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
// RunResponse answers POST /run. When Compile.OK is false, Results is empty.
|
||||
type RunResponse struct {
|
||||
Compile Compile `json:"compile"`
|
||||
Results []Result `json:"results"`
|
||||
}
|
||||
|
||||
// Compile is the build step. Python has none beyond a syntax check, which
|
||||
// reports the same way.
|
||||
type Compile struct {
|
||||
OK bool `json:"ok"`
|
||||
// Output is the compiler's output (warnings, errors), capped.
|
||||
Output string `json:"output,omitempty"`
|
||||
TimeMs int64 `json:"timeMs"`
|
||||
}
|
||||
|
||||
// Result is one test's outcome. Stdout and Stderr are capped (MaxOutput,
|
||||
// MaxStderr), with Truncated set when either was cut.
|
||||
type Result struct {
|
||||
Name string `json:"name"`
|
||||
Verdict string `json:"verdict"`
|
||||
TimeMs int64 `json:"timeMs"`
|
||||
ExitCode int `json:"exitCode"`
|
||||
Input string `json:"input"`
|
||||
Output string `json:"output"`
|
||||
Expected *string `json:"expected,omitempty"`
|
||||
Stderr string `json:"stderr,omitempty"`
|
||||
// Message explains RE and TLE: "killed by signal 11", "exceeded 2s".
|
||||
Message string `json:"message,omitempty"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
}
|
||||
|
||||
// Caps on what a result carries back.
|
||||
const (
|
||||
MaxOutput = 64 << 10
|
||||
MaxStderr = 8 << 10
|
||||
)
|
||||
|
||||
// LintRequest is POST /lint.
|
||||
type LintRequest struct {
|
||||
Lang string `json:"lang"`
|
||||
Source string `json:"source"`
|
||||
Files map[string]string `json:"files,omitempty"`
|
||||
}
|
||||
|
||||
// LintResponse answers POST /lint.
|
||||
type LintResponse struct {
|
||||
Diagnostics []Diagnostic `json:"diagnostics"`
|
||||
}
|
||||
|
||||
// Diagnostic is one problem in the source. Lines and columns are 1-based;
|
||||
// EndLine/EndCol are zero when the tool gives only a point.
|
||||
type Diagnostic struct {
|
||||
Line int `json:"line"`
|
||||
Col int `json:"col"`
|
||||
EndLine int `json:"endLine,omitempty"`
|
||||
EndCol int `json:"endCol,omitempty"`
|
||||
Severity string `json:"severity"` // "error", "warning" or "info"
|
||||
Message string `json:"message"`
|
||||
// Source is the tool: "g++", "clang-tidy", "ruff", "python".
|
||||
Source string `json:"source"`
|
||||
// Rule is the tool's check name when it has one ("unused-variable",
|
||||
// "bugprone-integer-division", "F401").
|
||||
Rule string `json:"rule,omitempty"`
|
||||
}
|
||||
Reference in New Issue
Block a user