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 \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 .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 }