Run and lint solutions on the site
Test and publish the site / test (push) Successful in 1m23s
Test and publish the site / publish (push) Failing after 4m22s

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:
2026-10-20 11:24:22 +01:00
co-authored by Claude Opus 5.5
parent 107ecab9da
commit c972fa9fd9
33 changed files with 4477 additions and 23 deletions
+30
View File
@@ -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
+72 -6
View File
@@ -15,10 +15,13 @@
# TWO JOBS
# test go vet + go test, and a vite build of site/web. The same checks
# as `make check` in site/.
# publish main only, after test: builds the image, pushes it to this
# Gitea's container registry as :<sha> and :latest, then pulls it
# into the web_server stack (its `usaco` service) and waits for it
# to be healthy — see "Deploying" in site/README.md.
# publish main only, after test: builds the two images, the site
# (Dockerfile) and its code runner (Dockerfile.runner), pushes
# each to this Gitea's container registry as :<sha> and :latest,
# then pulls them into the web_server stack (services
# `usaco-runner`, then `usaco`) and waits for each to be healthy —
# see "Deploying" in site/README.md. The runner goes first, so the
# new site never starts against an old runner.
#
# SECRETS (repo settings -> Actions -> Secrets)
# REGISTRY_USER a Gitea user that can write packages for adamf
@@ -34,6 +37,7 @@ on:
env:
IMAGE: adam-french.co.uk/adamf/usaco
RUNNER_IMAGE: adam-french.co.uk/adamf/usaco-runner
jobs:
test:
@@ -61,7 +65,12 @@ jobs:
# Read-only source, and named volumes for the module and build
# caches, for the reasons given in web_server's deploy.yaml. git
# is installed because internal/repo and internal/index test
# against real repositories.
# against real repositories. internal/runner's tests compile and
# run C++ and Python with the image's g++ and python3 (it runs as
# root, which the rlimits do not mind, and its sh is dash, whose
# ulimit they are written for); clang-tidy and ruff are not in
# it, so those tests skip, and the publish job's smoke test
# covers them in the runner image.
- name: Go - vet and test
shell: bash
run: |
@@ -106,7 +115,7 @@ jobs:
# the legacy builder, and is kept for any older daemon. This switches on BuildKit.
DOCKER_BUILDKIT: "1"
steps:
- name: Build and push the image
- name: Build the images
shell: bash
run: |
set -eu
@@ -116,14 +125,71 @@ jobs:
# Built natively on the host, so the image is amd64 — the only
# platform it runs on.
docker build -t "$IMAGE:$SHA" -t "$IMAGE:latest" "$SRC/site"
docker build -f "$SRC/site/Dockerfile.runner" -t "$RUNNER_IMAGE:$SHA" -t "$RUNNER_IMAGE:latest" "$SRC/site"
# The runner image is mostly other people's toolchains (g++,
# python3, clang-tidy, ruff on musl), which `go test` never sees.
# So before anything is pushed, start it with the production
# hardening and run one C++ program and one lint through it,
# from inside the container: the host has no curl, and busybox
# wget is enough.
- name: Smoke-test the runner image
shell: bash
run: |
set -eu
name="usaco-runner-ci-$SHA"
docker run -d --name "$name" --read-only --tmpfs /tmp:size=256m,exec \
--memory 1g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \
"$RUNNER_IMAGE:$SHA" >/dev/null
trap 'docker rm -f "$name" >/dev/null' EXIT
for i in $(seq 1 10); do
docker exec "$name" wget -qO- http://localhost:8081/health && break
sleep 1
done
post() { docker exec "$name" wget -qO- --header 'Content-Type: application/json' --post-data "$2" "http://localhost:8081/$1"; }
run=$(post run '{"lang":"cpp","source":"#include <bits/stdc++.h>\nint main(){int a,b;std::cin>>a>>b;std::cout<<a+b;}","tests":[{"name":"1","input":"1 2","output":"3"}]}')
echo "$run"
echo "$run" | grep -q '"verdict":"AC"'
lint=$(post lint '{"lang":"cpp","source":"#include <bits/stdc++.h>\nint main(){int a=1,b=2,c=3;return a==b==c;}"}')
echo "$lint"
echo "$lint" | grep -q '"source":"clang-tidy"'
lint=$(post lint '{"lang":"python","source":"import os\n"}')
echo "$lint"
echo "$lint" | grep -q '"rule":"F401"'
- name: Push the images
shell: bash
run: |
set -eu
docker push "$IMAGE:$SHA"
docker push "$IMAGE:latest"
docker push "$RUNNER_IMAGE:$SHA"
docker push "$RUNNER_IMAGE:latest"
- name: Remove the scratch directory
if: always()
shell: bash
run: rm -rf "$SRC"
# The runner first, the same way as the site below, so the new
# site never talks to an old runner. Pinning
# USACO_RUNNER_IMAGE_TAG in the site's .env makes this a no-op.
- name: Roll the runner onto the new image
working-directory: /home/adamf/deploy/web_server
shell: bash
run: |
set -eu
flock .compose.lock sh -c 'docker compose pull usaco-runner && docker compose up -d --no-deps usaco-runner'
for i in $(seq 1 30); do
status=$(docker inspect -f '{{.State.Health.Status}}' usaco-runner)
echo "usaco-runner: $status"
[ "$status" = healthy ] && exit 0
[ "$status" = unhealthy ] && break
sleep 5
done
docker logs --tail 50 usaco-runner
exit 1
# Put the new image live, exactly as job-tracker's workflow does
# for `jobs`: pull + up of the one service, under .compose.lock, which
# web_server's deploy.yaml and maintenance.yaml hold, then wait for the
+6
View File
@@ -66,3 +66,9 @@ S3_REGION=
S3_BUCKET=
S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY=
# --- Solve page -------------------------------------------------------------
# The runner service (cmd/usacorunner) that compiles, runs and lints code for
# the solve page, e.g. http://usaco-runner:8081. Blank turns Run and lint off;
# editing and saving code still work.
RUNNER_URL=
+2
View File
@@ -20,6 +20,8 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al
- **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network.
- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/<id>.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`.
- **Code runs in a separate service, never in the site.** The solve page's run/lint handlers (`handlers/run.go`) read the problem from the clone (`Server.Dir`, not the index, which truncates) and post to `cmd/usacorunner` through `runner.Client`; `internal/runner/types.go` is the contract between them. Tests fake it with `handlers.Runner`. The runner's own tests run real g++/python3/clang-tidy/ruff and skip whichever is missing.
## Conventions
- **Comments explain why, not what.** Preserve them, and update them when behaviour changes.
+59
View File
@@ -0,0 +1,59 @@
# =============================================================================
# The USACO site's code runner (cmd/usacorunner, internal/runner): compiles
# and runs a solution against its tests, and lints it, for the solve page.
# It runs whatever is submitted, so it is its own image and its own
# container, apart from the site, which holds every secret. Two stages:
#
# build compiles the Go service, as in Dockerfile (go.mod/go.sum first,
# so the dependency layer is cached across edits).
# runtime alpine with the toolchains the service shells out to:
# g++ + musl-dev builds C++ with the CLI's flags
# python3 runs Python, and checks its syntax
# clang-extra-tools clang-tidy, for lint (optional)
# ruff Python lint (optional)
# tini PID 1; see below
# A missing linter only means less lint; see internal/runner.
#
# The build context is site/, like Dockerfile: no problems are in the image.
# The site sends the source, its tests and any headers (debugging.h,
# leetcode.h, driver.h) with each request.
#
# It runs as uid 1000 and writes only to $TMPDIR (/tmp), one directory per
# request, which it removes afterwards. In production the container is
# hardened around that (web_server's docker-compose.yml, service
# usaco-runner):
# read_only root, with a tmpfs at /tmp that must NOT be noexec, because the
# compiled program runs from there; no network but the internal one the
# site shares; no capabilities; no-new-privileges; mem_limit, cpus and a
# pids_limit, which is what stops a fork bomb (the service does not set
# RLIMIT_NPROC; limits.go says why).
# Each program also gets its own rlimits (CPU, 512 MB address space, 64 MB
# files) and a wall-clock limit, set by the service per test.
#
# tini is PID 1 because a program's orphans are re-parented to PID 1, and
# the Go service never reaps processes it did not start: without an init, a
# fork bomb's children stay zombies after the kill and hold the pids_limit
# for good, and every later run fails to fork.
# =============================================================================
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY cmd ./cmd
COPY internal ./internal
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/usacorunner ./cmd/usacorunner
FROM alpine:3.22
RUN apk add --no-cache g++ musl-dev python3 clang-extra-tools ruff tini \
&& adduser -D -H -u 1000 app
COPY --from=build /out/usacorunner /app/usacorunner
USER app
ENV TMPDIR=/tmp
EXPOSE 8081
# busybox's wget, which is enough for plain HTTP on localhost.
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
CMD wget -qO- http://localhost:8081/health || exit 1
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["/app/usacorunner"]
+16 -2
View File
@@ -41,6 +41,8 @@ The site commits, so the laptop must pull before pushing. `usaco sync` does `pul
```
cmd/usacosite/ main: reads the environment, wires everything, registers routes
cmd/usacorunner/ the code runner service (its own image, Dockerfile.runner)
internal/runner/ compile, run, compare and lint, with limits; the site's client for it
internal/auth/ is this request the admin? (asks the site backend; copied from job-tracker)
internal/repo/ the clone: sync, and edit-commit-push with one replay on rejection
internal/index/ reads the clone into memory: problems, files, tests, git dates
@@ -73,6 +75,10 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
| `GET /usaco/api/problems/<name>/reviews/<id>/audio` | admin | the review's recording, with range support; 404 if it was not kept |
| `DELETE /usaco/api/problems/<name>/reviews/<id>` | admin | removes the review and its recording |
| `POST /usaco/api/problems/<name>/status` | admin | `{to: solving\|solved\|skipped}`: moves the directory |
| `GET /usaco/api/problems/<name>/code` | admin | the solve page's start: `{io, leetcode, languages, default, runner, code: {cpp, python}}`, each language's saved source or a starter from `template.cpp`/`template.py` |
| `POST /usaco/api/problems/<name>/run` | admin | `{lang, source, mode: tests\|custom, input?}`: compiles once and runs the saved tests (or the custom input) on the runner; answers its verdicts. 503 without `RUNNER_URL` |
| `POST /usaco/api/problems/<name>/lint` | admin | `{lang, source}`: the runner's diagnostics (g++ and clang-tidy, or python and ruff) |
| `PUT /usaco/api/problems/<name>/code` | admin | `{lang, source}`: commits `main.cpp`, or `main.py` (`sol.py` where that is the existing file), as "Edit <name>" |
| `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull |
| `GET /usaco/api/health` | open | 200 once the clone is indexed |
@@ -113,8 +119,8 @@ The site's `docker-compose.yml` runs the published image as service `usaco`, wit
A push to `main` that touches `site/` or `.gitea/workflows/` runs `.gitea/workflows/ci.yaml` at the repo root. It does the following:
1. Tests.
2. Builds the image from `site/` and pushes it as `adam-french.co.uk/adamf/usaco:<sha>` and `:latest`.
3. Rolls the site onto the new image and waits for the healthcheck.
2. Builds both images from `site/`, smoke-tests the runner, and pushes them as `adam-french.co.uk/adamf/usaco:<sha>` and `adam-french.co.uk/adamf/usaco-runner:<sha>`, each also as `:latest`.
3. Rolls `usaco-runner` and then the site onto the new images, waiting for each healthcheck.
Problem commits don't match the path filter, so they never rebuild the image. The webhook brings them in.
@@ -164,6 +170,14 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
- **The recording.** It is too big for git. With all five `S3_*` variables set it is kept in that bucket as `<name>/<id>.<ext>` and the page gets a player; otherwise it is thrown away once transcribed. In web_server that is a private Garage bucket, never the public `uploads` one. A recording whose review fails is deleted again.
- **Privacy.** A review is a transcript of the admin talking, so reviews and their count are blanked for everyone else, even on solved problems.
## Solve page
`/usaco/p/<name>/solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`.
- **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it.
- **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `<io>.in` with that file also on stdin, `<io>.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s.
- **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped.
## Things that are easy to get wrong
- **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time.
+70
View File
@@ -0,0 +1,70 @@
// Command usacorunner compiles and runs solutions against their tests, and
// lints them, for the USACO site's solve page (internal/runner). It runs
// untrusted code, so it is its own service: the site holds secrets and
// this holds none, and in production its container has no outside network,
// a read-only root, an exec-able tmpfs at /tmp and tight memory, CPU and
// pids limits (Dockerfile.runner lists them). Only the site talks to it.
//
// It reads PORT (default 8081) and MAX_PARALLEL (default 2): how many runs
// and lints may be in progress at once. More only makes each slower, and
// a timing that depends on the neighbours is no use for a time limit.
package main
import (
"log"
"net/http"
"os"
"sort"
"strconv"
"strings"
"time"
"adam-french.co.uk/usaco-site/internal/runner"
)
func main() {
maxParallel := 2
if v := os.Getenv("MAX_PARALLEL"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
log.Fatalf("MAX_PARALLEL=%q is not a positive number", v)
}
maxParallel = n
}
// The compilers are what the image is for: without g++ or python3 the
// runner still answers, but every run in that language fails to build.
var have, missing []string
for bin, ok := range runner.Tools() {
if ok {
have = append(have, bin)
} else {
missing = append(missing, bin)
}
}
sort.Strings(have)
sort.Strings(missing)
log.Printf("[runner] tools: %s", strings.Join(have, ", "))
if len(missing) > 0 {
log.Printf("[runner] not installed: %s", strings.Join(missing, ", "))
}
addr := ":" + getenv("PORT", "8081")
srv := &http.Server{
Addr: addr,
Handler: runner.Handler(maxParallel),
ReadHeaderTimeout: 10 * time.Second,
// Above the runner's own 60s budget per request, which is what
// actually bounds a response.
WriteTimeout: 75 * time.Second,
}
log.Printf("listening on %s, %d at a time", addr, maxParallel)
log.Fatal(srv.ListenAndServe())
}
func getenv(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
+15 -4
View File
@@ -1,8 +1,8 @@
// Command usacosite serves the USACO practice log at /usaco/: the problems
// from adamf/usaco on the site's Gitea, their solutions and tests, and a few
// admin edits (problem link, notes, statement, status), Claude-written
// explanations and reviews of recorded explanations that it commits back to
// git.
// admin edits (problem link, notes, statement, status, the solution itself
// on the solve page), Claude-written explanations and reviews of recorded
// explanations that it commits back to git.
//
// It is built to sit behind adam-french.co.uk's nginx and borrow its login
// (internal/auth), like the job tracker. There is no database: the server
@@ -27,6 +27,7 @@ import (
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/handlers"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/runner"
"adam-french.co.uk/usaco-site/internal/transcribe"
)
@@ -113,6 +114,16 @@ func main() {
log.Println("[review] S3_ENDPOINT is not set: recordings are not kept")
}
// RUNNER
// Optional: the solve page runs and lints code through the sandboxed
// runner service. Without it the page still edits and saves code.
if u := os.Getenv("RUNNER_URL"); u != "" {
srv.Runner = runner.NewClient(u)
log.Printf("[runner] code runs on %s", u)
} else {
log.Println("[runner] RUNNER_URL is not set: running and linting code are off")
}
rp, err := repo.New(repo.Config{
Dir: filepath.Join(dataDir, "repo"),
Remote: remote,
@@ -126,7 +137,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
srv.Repo = rp
srv.Repo, srv.Dir = rp, rp.Dir()
// SYNC LOOP
// One goroutine does every pull, so webhook bursts coalesce: a trigger
+21
View File
@@ -9,6 +9,10 @@
# so nothing here can touch your working tree or the real remote. Only
# committed work shows up: it is a clone, not the working tree.
#
# The solve page's runs and lint go to the `runner` service (Dockerfile.runner),
# hardened as it is in production, apart from the network: here it shares the
# default one. It publishes no port; the site reaches it as runner:8081.
#
# This is NOT how it runs in production. There it is one service in the main
# site's docker-compose.yml, behind its nginx, cloning from Gitea and
# borrowing the site's login; see README.md.
@@ -36,9 +40,26 @@ services:
TRANSCRIBE_API_KEY: ${TRANSCRIBE_API_KEY:-${OPENAI_API_KEY:-}}
TRANSCRIBE_URL: ${TRANSCRIBE_URL:-}
TRANSCRIBE_MODEL: ${TRANSCRIBE_MODEL:-}
RUNNER_URL: http://runner:8081
volumes:
- ..:/seed:ro
- usaco-data:/data
depends_on:
- runner
runner:
build:
context: .
dockerfile: Dockerfile.runner
read_only: true
# Not noexec: the compiled program runs from here.
tmpfs:
- /tmp:size=256m,exec
mem_limit: 1g
cpus: 2
pids_limit: 128
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
volumes:
usaco-data:
+26 -9
View File
@@ -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):
+542
View File
@@ -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
}
+301
View File
@@ -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)
}
}
+30
View File
@@ -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
+74
View File
@@ -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)
}
+207
View File
@@ -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})
}
+99
View File
@@ -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)
}
+277
View File
@@ -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
}
+313
View File
@@ -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
}
+200
View File
@@ -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")
}
}
+255
View File
@@ -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"
}
+273
View File
@@ -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)
}
}
+122
View File
@@ -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"`
}
+198
View File
@@ -8,7 +8,16 @@
"name": "usaco-site-web",
"version": "0.0.0",
"dependencies": {
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/language": "^6.12.4",
"@codemirror/lint": "^6.9.7",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5",
"@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
"highlight.js": "^11.11.1",
"katex": "^0.16.25",
@@ -72,6 +81,110 @@
"node": ">=6.9.0"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.11.1",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz",
"integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-cpp": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz",
"integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@lezer/cpp": "^1.0.0"
}
},
"node_modules/@codemirror/lang-python": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz",
"integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.3.2",
"@codemirror/language": "^6.8.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.2.1",
"@lezer/python": "^1.1.4"
}
},
"node_modules/@codemirror/language": {
"version": "6.12.4",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
"integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "6.7.2",
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.2.tgz",
"integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.37.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.6",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.43.13",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.13.tgz",
"integrity": "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
@@ -563,6 +676,58 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lezer/common": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz",
"integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==",
"license": "MIT"
},
"node_modules/@lezer/cpp": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.6.tgz",
"integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.10",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/python": {
"version": "1.1.19",
"resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz",
"integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
"license": "MIT"
},
"node_modules/@napi-rs/lzma-linux-x64-gnu": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
@@ -1425,6 +1590,21 @@
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"license": "Python-2.0"
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
"integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/commander": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
@@ -1434,6 +1614,12 @@
"node": ">= 12"
}
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -2071,6 +2257,12 @@
"node": ">=0.10.0"
}
},
"node_modules/style-mod": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
"license": "MIT"
},
"node_modules/tailwindcss": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz",
@@ -2225,6 +2417,12 @@
"peerDependencies": {
"vue": "^3.5.0"
}
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
}
}
}
+9
View File
@@ -12,7 +12,16 @@
"preview": "vite preview"
},
"dependencies": {
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/language": "^6.12.4",
"@codemirror/lint": "^6.9.7",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5",
"@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
"highlight.js": "^11.11.1",
"katex": "^0.16.25",
+27 -2
View File
@@ -1,12 +1,18 @@
<script setup>
/**
* Root: the header with the page links, and the outlet.
*
* A route with meta.wide (the solve page) gets the whole window instead of
* the reading column, and on a desktop the shell is exactly the viewport
* tall so the page can split the space under the header into panes.
*/
import { RouterLink, RouterView } from "vue-router";
import { RouterLink, RouterView, useRoute } from "vue-router";
const route = useRoute();
</script>
<template>
<div class="shell">
<div class="shell" :class="{ wide: route.meta.wide }">
<header class="top">
<RouterLink to="/" class="brand">USACO practice</RouterLink>
<nav>
@@ -29,6 +35,25 @@ import { RouterLink, RouterView } from "vue-router";
margin: 0 auto;
padding: 0 16px 48px;
}
.shell.wide {
max-width: none;
padding-bottom: 16px;
}
.shell.wide .top {
margin-bottom: 12px;
}
@media (min-width: 900px) {
.shell.wide {
height: 100vh;
height: 100dvh;
display: flex;
flex-direction: column;
}
.shell.wide main {
flex: 1;
min-height: 0;
}
}
.top {
display: flex;
flex-wrap: wrap;
+9
View File
@@ -51,3 +51,12 @@ export const deleteReview = (name, id) =>
// For an <audio> src: the browser fetches it, with ranges for seeking.
export const reviewAudioUrl = (name, id) =>
`${BASE}/problems/${encodeURIComponent(name)}/reviews/${encodeURIComponent(id)}/audio`;
// The solve page (admin only). run and lint go to the code runner
// (RUNNER_URL) and answer when it does: a run can take a minute.
export const getCode = (name) => request("GET", `/problems/${encodeURIComponent(name)}/code`);
// body: { lang, source, mode: "tests" | "custom", input? }
export const runCode = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/run`, body);
export const lintCode = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/lint`, body);
// Commits the source as the problem's solution file in that language.
export const saveCode = (name, body) => request("PUT", `/problems/${encodeURIComponent(name)}/code`, body);
+208
View File
@@ -0,0 +1,208 @@
<script setup>
/**
* The solve page's editor: CodeMirror 6 behind a v-model, in the paper
* palette (the colours are CodeBlock's highlight.js ones, so code reads the
* same in both).
*
* Each language keeps its own EditorState, rather than one state whose
* language sits in a Compartment: reconfiguring a shared state would give
* the two languages one undo history, so Ctrl+Z after a switch would bring
* back the other language's code. With a state each, switching back also
* restores the cursor and history where they were.
*
* Diagnostics come in as a prop, already fetched by the page (its lint call
* is remote and debounced by the page), and are pushed with setDiagnostics
* rather than through a linter() source the editor would schedule itself.
* CodeMirror maps them through later edits until the next set arrives.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { basicSetup } from "codemirror";
import { EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { indentWithTab } from "@codemirror/commands";
import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language";
import { lintGutter, setDiagnostics } from "@codemirror/lint";
import { cpp } from "@codemirror/lang-cpp";
import { python } from "@codemirror/lang-python";
import { tags as t } from "@lezer/highlight";
const props = defineProps({
modelValue: { type: String, required: true },
lang: { type: String, required: true },
// The server's: 1-based line/col, endLine/endCol optional.
diagnostics: { type: Array, default: () => [] },
label: { type: String, default: "Code" },
});
const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
// The workspace's styles: clang-format's two spaces for C++, PEP 8's four.
const LANGS = {
cpp: () => [cpp(), indentUnit.of(" ")],
c: () => [cpp(), indentUnit.of(" ")],
python: () => [python(), indentUnit.of(" ")],
};
const highlight = HighlightStyle.define([
{ tag: t.comment, color: "#6a737d", fontStyle: "italic" },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.definitionKeyword, t.moduleKeyword, t.modifier, t.self], color: "#a3268d" },
{ tag: [t.typeName, t.className, t.namespace, t.standard(t.typeName)], color: "#0b6e99" },
{ tag: [t.string, t.special(t.string), t.character, t.escape], color: "#1a7f37" },
{ tag: [t.number, t.bool, t.null, t.atom, t.literal], color: "#b35900" },
{
tag: [t.function(t.variableName), t.function(t.definition(t.variableName)), t.function(t.propertyName)],
color: "#5a3fc0",
},
{ tag: [t.processingInstruction, t.meta, t.special(t.name)], color: "#8250df" },
{ tag: t.invalid, color: "var(--color-ink-danger)" },
]);
const theme = EditorView.theme(
{
"&": {
height: "100%",
fontSize: "0.8125rem",
color: "var(--color-ink-soft)",
backgroundColor: "var(--color-paper)",
},
// The wrapper draws focus, and the site's global :focus-visible ring
// would otherwise land on the contenteditable inside.
"&.cm-focused": { outline: "none" },
".cm-content:focus-visible": { outline: "none" },
".cm-scroller": { fontFamily: "var(--font-mono)", lineHeight: "1.55" },
".cm-content": { caretColor: "var(--color-ink)", padding: "12px 0" },
".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--color-ink)" },
".cm-gutters": {
backgroundColor: "var(--color-paper)",
color: "var(--color-ink-faint)",
borderRight: "1px solid var(--color-line-soft)",
},
".cm-lineNumbers .cm-gutterElement": { padding: "0 10px 0 12px" },
".cm-activeLine": { backgroundColor: "rgba(0, 0, 0, 0.03)" },
".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--color-ink)" },
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
{ backgroundColor: "#d7e6fb" },
".cm-selectionMatch": { backgroundColor: "#eef3e2" },
"&.cm-focused .cm-matchingBracket": { backgroundColor: "var(--color-paper-shade)", outline: "1px solid var(--color-line)" },
".cm-tooltip": {
border: "1px solid var(--color-line)",
borderRadius: "4px",
backgroundColor: "var(--color-paper)",
color: "var(--color-ink)",
},
".cm-diagnostic": { fontFamily: "var(--font-mono)", fontSize: "0.8rem" },
".cm-diagnostic-error": { borderLeftColor: "var(--color-ink-danger)" },
".cm-diagnostic-warning": { borderLeftColor: "var(--color-solving)" },
".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" },
".cm-diagnosticSource": { color: "var(--color-ink-muted)" },
".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" },
},
{ dark: false },
);
// The page also listens for these on the window, for when the editor is not
// focused; stopping them here keeps one press from running twice, and keeps
// basicSetup's Mod-Enter (insert a blank line) out of the way.
const pageKeys = Prec.highest(
keymap.of([
{ key: "Mod-Shift-Enter", run: () => (emit("submit"), true), stopPropagation: true },
{ key: "Mod-Enter", run: () => (emit("run"), true), stopPropagation: true },
{ key: "Mod-s", run: () => (emit("save"), true), preventDefault: true, stopPropagation: true },
]),
);
const host = ref(null);
let view = null;
const states = new Map();
function newState(doc, lang) {
return EditorState.create({
doc,
extensions: [
pageKeys,
basicSetup,
keymap.of([indentWithTab]),
(LANGS[lang] || (() => []))(),
syntaxHighlighting(highlight),
lintGutter(),
theme,
EditorView.contentAttributes.of({ "aria-label": props.label }),
EditorView.updateListener.of((u) => {
if (u.docChanged) emit("update:modelValue", u.state.doc.toString());
}),
],
});
}
// The server's positions as document offsets. Columns are taken as
// characters; anything past the end of a line or the document is clamped,
// since the source may have moved on since the lint ran. Without an end
// the mark covers the word at the start, or the rest of the line.
function toDiagnostic(d, doc) {
const lineAt = (n) => doc.line(Math.min(Math.max(n || 1, 1), doc.lines));
const at = (lineNo, col) => {
const line = lineAt(lineNo);
return line.from + Math.min(Math.max((col || 1) - 1, 0), line.length);
};
const from = at(d.line, d.col);
let to = d.endLine > 0 ? at(d.endLine, d.endCol || 1) : from;
if (to <= from) {
const line = doc.lineAt(from);
const word = /^\w+/.exec(line.text.slice(from - line.from));
to = word ? from + word[0].length : line.to;
}
const severity = ["error", "warning", "info"].includes(d.severity) ? d.severity : "info";
const source = [d.source, d.rule].filter(Boolean).join(" ");
return { from, to, severity, message: d.message, ...(source ? { source } : {}) };
}
function pushDiagnostics() {
const doc = view.state.doc;
view.dispatch(setDiagnostics(view.state, props.diagnostics.map((d) => toDiagnostic(d, doc))));
}
onMounted(() => {
view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value });
states.set(props.lang, view.state);
});
onBeforeUnmount(() => view?.destroy());
// The page sets the language and its source in one go, so they are watched
// together: a new language swaps in that language's state; a new value in
// the same language (Reset, Save's commit) replaces the text as an edit,
// so Ctrl+Z can bring the old text back.
watch(
() => [props.lang, props.modelValue],
([lang, value], [oldLang]) => {
if (!view) return;
if (lang !== oldLang) {
states.set(oldLang, view.state);
const kept = states.get(lang);
view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang));
pushDiagnostics();
} else if (value !== view.state.doc.toString()) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
}
},
);
watch(() => props.diagnostics, () => view && pushDiagnostics());
defineExpose({ focus: () => view?.focus() });
</script>
<template>
<div ref="host" class="editor"></div>
</template>
<style scoped>
.editor {
height: 100%;
min-height: 0;
border: 1px solid var(--color-line-soft);
border-radius: 6px;
overflow: hidden;
background: var(--color-paper);
}
.editor:focus-within {
border-color: var(--color-ink-muted);
}
</style>
+314
View File
@@ -0,0 +1,314 @@
<script setup>
/**
* The solve page's bottom panel: the custom input box, and what the last run
* came back with, a tab per test (or one for a custom run). A compile
* failure gets a tab of its own and there are no results; warnings from a
* build that worked get one too, so they are not lost behind the verdicts.
*
* After a run the panel opens the tab worth reading first: the compile
* error, else the first test that failed, else the first test.
*/
import { computed, ref, watch } from "vue";
import CodeBlock from "@/components/CodeBlock.vue";
import { MOD_KEY } from "@/format";
const props = defineProps({
// The run response, plus the mode it was run in.
result: { type: Object, default: null },
// "custom" or "tests" while a run is in flight.
running: { type: String, default: "" },
error: { type: String, default: "" },
modelValue: { type: String, default: "" },
});
defineEmits(["update:modelValue"]);
const VERDICTS = {
AC: "Accepted",
WA: "Wrong answer",
RE: "Runtime error",
TLE: "Time limit exceeded",
unchecked: "Ran",
};
const tab = ref("custom");
const compile = computed(() => props.result?.compile);
const results = computed(() => props.result?.results || []);
const warnings = computed(() => compile.value?.ok && compile.value.output?.trim());
const tabs = computed(() => {
const out = [{ id: "custom", label: "Custom input" }];
if (compile.value && !compile.value.ok) out.push({ id: "compile", label: "Compile error", verdict: "bad" });
if (warnings.value) out.push({ id: "warnings", label: "Warnings" });
results.value.forEach((r, i) => {
const label = props.result.mode === "custom" ? "Output" : `Test ${r.name}`;
out.push({ id: `r${i}`, label, verdict: r.verdict });
});
return out;
});
watch(
() => props.result,
(r) => {
if (!r) return;
if (!r.compile?.ok) {
tab.value = "compile";
return;
}
const failed = r.results.findIndex((x) => x.verdict !== "AC" && x.verdict !== "unchecked");
tab.value = r.results.length ? `r${Math.max(failed, 0)}` : "custom";
},
);
const current = computed(() => (tab.value.startsWith("r") ? results.value[Number(tab.value.slice(1))] : null));
const summary = computed(() => {
const c = compile.value;
if (!c) return "";
const build = `${c.timeMs} ms compile`;
if (!c.ok) return `Compile error · ${build}`;
const rs = results.value;
if (props.result.mode === "custom") {
return rs.length ? `${VERDICTS[rs[0].verdict] || rs[0].verdict} in ${rs[0].timeMs} ms · ${build}` : build;
}
if (!rs.length) return `No saved tests · ${build}`;
const passed = rs.filter((r) => r.verdict === "AC").length;
return `${passed}/${rs.length} passed · ${build}`;
});
const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plain" : "bad");
</script>
<template>
<div class="results card">
<div class="bar">
<div class="tabs" role="tablist" aria-label="Run results">
<button
v-for="tb in tabs"
:id="`tab-${tb.id}`"
:key="tb.id"
type="button"
role="tab"
:aria-selected="tab === tb.id"
aria-controls="run-panel"
:class="{ on: tab === tb.id }"
@click="tab = tb.id"
>
<span v-if="tb.verdict" class="dot" :class="verdictClass(tb.verdict)" aria-hidden="true"></span>
{{ tb.label }}
</button>
</div>
<span v-if="running" class="working" role="status">
{{ running === "tests" ? "Running the saved tests…" : "Running on your input…" }}
</span>
<span v-else-if="summary" class="summary muted" role="status">{{ summary }}</span>
</div>
<div id="run-panel" class="body" role="tabpanel" :aria-labelledby="`tab-${tab}`">
<p v-if="error" class="error">{{ error }}</p>
<label v-if="tab === 'custom'" class="custom">
<span class="muted">
Input for Run ({{ MOD_KEY }}+Enter). Submit ({{ MOD_KEY }}+Shift+Enter) runs the saved tests instead.
</span>
<textarea
:value="modelValue"
rows="6"
spellcheck="false"
placeholder="stdin for your program"
@input="$emit('update:modelValue', $event.target.value)"
></textarea>
</label>
<template v-else-if="tab === 'compile'">
<CodeBlock :content="compile.output || 'The compiler said nothing.'" />
</template>
<template v-else-if="tab === 'warnings'">
<CodeBlock :content="compile.output" />
</template>
<div v-else-if="current" class="result">
<p class="facts">
<span class="badge verdict" :class="verdictClass(current.verdict)">
{{ VERDICTS[current.verdict] || current.verdict }}
</span>
<span class="muted">{{ current.timeMs }} ms</span>
<span v-if="current.exitCode" class="muted">exit code {{ current.exitCode }}</span>
<span v-if="current.message" class="error">{{ current.message }}</span>
</p>
<p v-if="current.truncated" class="muted note">The output was cut short by the runner.</p>
<div>
<p class="filename muted">Input</p>
<CodeBlock v-if="current.input" :content="current.input" />
<p v-else class="muted empty">(empty)</p>
</div>
<div class="io">
<div>
<p class="filename muted">Output</p>
<CodeBlock v-if="current.output" :content="current.output" />
<p v-else class="muted empty">(empty)</p>
</div>
<div v-if="current.expected !== undefined && current.expected !== null">
<p class="filename muted">Expected</p>
<CodeBlock v-if="current.expected" :content="current.expected" />
<p v-else class="muted empty">(empty)</p>
</div>
</div>
<div v-if="current.stderr">
<p class="filename muted">stderr</p>
<CodeBlock :content="current.stderr" />
</div>
</div>
</div>
</div>
</template>
<style scoped>
.results {
display: flex;
flex-direction: column;
min-height: 0;
height: 100%;
}
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 4px 12px;
padding: 6px 8px;
border-bottom: 1px solid var(--color-line-soft);
}
.tabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
min-width: 0;
}
.tabs button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
font-size: 0.8rem;
color: var(--color-ink-muted);
background: var(--color-paper);
cursor: pointer;
white-space: nowrap;
}
.tabs button:hover {
color: var(--color-ink);
}
.tabs button.on {
border-color: var(--color-ink);
color: var(--color-ink);
background: var(--color-paper-shade);
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-skipped);
}
.dot.ok {
background: var(--color-solved);
}
.dot.bad {
background: var(--color-ink-danger);
}
.summary,
.working {
font-size: 0.85rem;
}
/* The pulsing dot of the problem page's jobs: the request is still open. */
.working::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
margin-right: 8px;
border-radius: 50%;
background: var(--color-solving);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.25;
}
}
@media (prefers-reduced-motion: reduce) {
.working::before {
animation: none;
}
}
.body {
flex: 1;
min-height: 0;
overflow: auto;
padding: 10px 12px 12px;
display: grid;
align-content: start;
gap: 10px;
}
.custom {
display: grid;
gap: 6px;
font-size: 0.8rem;
}
.custom textarea {
width: 100%;
padding: 8px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-family: var(--font-mono);
font-size: 0.8125rem;
line-height: 1.55;
color: var(--color-ink);
background: var(--color-paper);
resize: vertical;
}
.result {
display: grid;
gap: 10px;
min-width: 0;
}
.result > div {
min-width: 0;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 12px;
font-size: 0.875rem;
}
.verdict.ok {
color: var(--color-solved);
border-color: currentColor;
}
.verdict.bad {
color: var(--color-ink-danger);
border-color: currentColor;
}
.note,
.empty {
font-size: 0.8rem;
}
.io {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
min-width: 0;
}
.io > div {
min-width: 0;
}
.filename {
font-family: var(--font-mono);
font-size: 0.8rem;
margin-bottom: 4px;
}
</style>
+3
View File
@@ -23,3 +23,6 @@ export function dayKey(date) {
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
// The modifier the editor's shortcuts use, as the keyboard labels it.
export const MOD_KEY = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? "⌘" : "Ctrl";
+8
View File
@@ -12,6 +12,14 @@ export default createRouter({
routes: [
{ path: "/", name: "list", component: () => import("@/views/ProblemList.vue") },
{ path: "/p/:name", name: "problem", component: () => import("@/views/ProblemPage.vue"), props: true },
// wide: App drops its column width so the editor gets the whole window.
{
path: "/p/:name/solve",
name: "solve",
component: () => import("@/views/SolvePage.vue"),
props: true,
meta: { wide: true },
},
{ path: "/stats", name: "stats", component: () => import("@/views/StatsPage.vue") },
{ path: "/cli", name: "cli", component: () => import("@/views/CliPage.vue") },
{ path: "/:pathMatch(.*)*", redirect: "/" },
+4
View File
@@ -332,6 +332,7 @@ const moves = computed(() => {
>
{{ t.label }}
</button>
<RouterLink :to="`/p/${problem.name}/solve`" class="btn solve">Solve</RouterLink>
</div>
<div v-if="saving || busy.length" class="admin-row status" role="status">
<span v-if="saving" class="muted">Saving to git…</span>
@@ -581,6 +582,9 @@ h2 {
display: none;
}
}
.btn.solve {
text-decoration: none;
}
.btn.tool.on {
border-color: var(--color-ink);
background: var(--color-paper-shade);
+653
View File
@@ -0,0 +1,653 @@
<script setup>
/**
* Solve a problem in the browser (admin only): the statement and saved
* tests on the left, an editor on the right with Run (the custom input),
* Submit (the saved tests) and Save (a commit, like the CLI's).
*
* What is typed is kept as a draft in this browser per problem and language
* until it is saved or reset, so leaving the page loses nothing and there
* is no "unsaved changes" prompt. Runs and lints are plain requests to the
* server, which passes them to the code runner: a run answers when it has
* finished, which can take up to a minute.
*/
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { RouterLink } from "vue-router";
import CodeBlock from "@/components/CodeBlock.vue";
import CodeEditor from "@/components/CodeEditor.vue";
import RunResults from "@/components/RunResults.vue";
import { markdown } from "@/markdown";
import { getCode, getMe, getProblem, lintCode, runCode, saveCode } from "@/api";
import { LANG_LABELS, MOD_KEY, STATUS_LABELS, title } from "@/format";
const props = defineProps({ name: { type: String, required: true } });
const md = markdown();
const problem = ref(null);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
// GET /code: the languages, and per language the repo's file or a starter.
const info = ref(null);
const lang = ref("");
const source = ref("");
const customInput = ref("");
const running = ref("");
const result = ref(null);
const runError = ref("");
const saving = ref(false);
const saveError = ref("");
const notice = ref("");
const diagnostics = ref([]);
const linted = ref(false);
const lintError = ref("");
const statementHtml = computed(() => (problem.value?.statement ? md.render(problem.value.statement) : ""));
const current = computed(() => info.value?.code[lang.value]);
const dirty = computed(() => !!current.value && source.value !== current.value.source);
const busy = computed(() => !!running.value || saving.value);
const canRun = computed(() => !!info.value?.runner && !busy.value);
// A starter can be saved as it is: that is how a language gets its file.
const canSave = computed(() => !!current.value && !busy.value && (dirty.value || !current.value.saved));
const codeStatus = computed(() => {
if (!current.value) return "";
if (dirty.value) return "Unsaved draft";
if (current.value.saved) return `Saved in repo as ${current.value.path}`;
return "Starter template — not in the repo yet";
});
async function load() {
flushDraft();
clearTimeout(lintTimer);
const name = props.name;
loading.value = true;
error.value = "";
info.value = null;
result.value = null;
running.value = "";
runError.value = "";
saveError.value = "";
notice.value = "";
diagnostics.value = [];
linted.value = false;
try {
const [p, me] = await Promise.all([getProblem(name), getMe().catch(() => ({ admin: false }))]);
if (name !== props.name) return;
problem.value = p;
admin.value = me.admin;
customInput.value = p.sample?.content || "";
// The code endpoints are admin-only; asking anyway would send the
// visitor to the login page instead of explaining.
if (!me.admin) return;
const c = await getCode(name);
if (name !== props.name) return;
info.value = c;
open(c.code[c.default] ? c.default : c.languages[0]);
} catch (e) {
if (name !== props.name) return;
problem.value = null;
error.value = e.status === 404 ? "No such problem." : e.message;
} finally {
if (name === props.name) loading.value = false;
}
}
// Shows a language: its draft if there is one, else the repo's file or the
// starter.
function open(l) {
lang.value = l;
source.value = readDraft(props.name, l) ?? info.value.code[l].source;
diagnostics.value = [];
linted.value = false;
lintError.value = "";
notice.value = "";
saveError.value = "";
lintSoon();
}
function switchLang(l) {
if (l === lang.value || busy.value) return;
flushDraft();
open(l);
}
function reset() {
const c = current.value;
const to = c.saved ? "the saved code" : "the starter template";
if (dirty.value && !window.confirm(`Discard your draft and go back to ${to}?`)) return;
source.value = c.source;
dropDraft(props.name, lang.value);
}
// ---- drafts ----
// Written half a second after typing stops. The pending write carries its
// own problem and language, so a switch or navigation flushes it to the
// right key.
const draftKey = (name, l) => `usaco:draft:${name}:${l}`;
let draftTimer = null;
let pendingDraft = null;
function readDraft(name, l) {
try {
return localStorage.getItem(draftKey(name, l));
} catch {
return null; // Storage blocked (private mode, site data off): no drafts.
}
}
function scheduleDraft() {
if (!current.value) return;
pendingDraft = { name: props.name, lang: lang.value, source: source.value, saved: current.value.source };
clearTimeout(draftTimer);
draftTimer = setTimeout(flushDraft, 500);
}
function flushDraft() {
clearTimeout(draftTimer);
const d = pendingDraft;
pendingDraft = null;
if (!d) return;
try {
// Typing back to what is saved is not a draft.
if (d.source === d.saved) localStorage.removeItem(draftKey(d.name, d.lang));
else localStorage.setItem(draftKey(d.name, d.lang), d.source);
} catch {
// As in readDraft.
}
}
function dropDraft(name, l) {
if (pendingDraft?.name === name && pendingDraft.lang === l) {
clearTimeout(draftTimer);
pendingDraft = null;
}
try {
localStorage.removeItem(draftKey(name, l));
} catch {
// As in readDraft.
}
}
// ---- lint ----
// 1.5 s after typing stops, and at once on Run and Submit. Only the newest
// request counts, and only while the text is still what was linted: an
// edit since then has already scheduled another.
let lintTimer = null;
let lintSeq = 0;
function lintSoon() {
clearTimeout(lintTimer);
if (info.value?.runner) lintTimer = setTimeout(lintNow, 1500);
}
async function lintNow() {
clearTimeout(lintTimer);
if (!info.value?.runner) return;
const seq = ++lintSeq;
const name = props.name;
const l = lang.value;
const src = source.value;
try {
const r = await lintCode(name, { lang: l, source: src });
if (seq !== lintSeq || name !== props.name || l !== lang.value || src !== source.value) return;
diagnostics.value = r.diagnostics || [];
linted.value = true;
lintError.value = "";
} catch (e) {
if (seq === lintSeq) lintError.value = e.message;
}
}
const lintSummary = computed(() => {
const count = (s) => diagnostics.value.filter((d) => d.severity === s).length;
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
const [e, w, i] = [count("error"), count("warning"), count("info")];
return {
errors: e ? plural(e, "error") : "",
rest: [w && plural(w, "warning"), i && plural(i, "note")].filter(Boolean).join(" · "),
};
});
watch(source, () => {
notice.value = "";
scheduleDraft();
lintSoon();
});
// ---- run, submit, save ----
async function run(mode) {
if (!canRun.value) return;
const name = props.name;
const body = { lang: lang.value, source: source.value, mode };
if (mode === "custom") body.input = customInput.value;
running.value = mode;
runError.value = "";
lintNow();
try {
const r = await runCode(name, body);
if (name === props.name) result.value = { ...r, mode };
} catch (e) {
if (name === props.name) runError.value = e.message;
} finally {
if (name === props.name) running.value = "";
}
}
async function save() {
if (!canSave.value) return;
const name = props.name;
const l = lang.value;
const src = source.value;
saving.value = true;
saveError.value = "";
notice.value = "";
try {
const { path } = await saveCode(name, { lang: l, source: src });
if (name !== props.name) return;
info.value.code[l] = { ...info.value.code[l], path, source: src, saved: true };
// Typing during the commit made a newer draft; that one stays.
if (source.value === src) dropDraft(name, l);
notice.value = `Committed ${path}`;
} catch (e) {
if (name === props.name) saveError.value = e.message;
} finally {
if (name === props.name) saving.value = false;
}
}
// The editor handles these itself while it has focus (and stops them);
// this is for everywhere else on the page, the custom input included.
function onKey(e) {
if (!info.value || !(e.ctrlKey || e.metaKey) || e.altKey) return;
if (e.key === "Enter") {
e.preventDefault();
run(e.shiftKey ? "tests" : "custom");
} else if (e.key.toLowerCase() === "s" && !e.shiftKey) {
e.preventDefault();
save();
}
}
// A draft still in its half second would be lost with the tab.
onMounted(() => {
window.addEventListener("keydown", onKey);
window.addEventListener("pagehide", flushDraft);
});
onUnmounted(() => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pagehide", flushDraft);
clearTimeout(lintTimer);
flushDraft();
});
// ---- the divider between the panes ----
// A share of the width, remembered in this browser.
const SPLIT_KEY = "usaco:solve:split";
const panes = ref(null);
const split = ref(readSplit());
function readSplit() {
try {
const v = Number(localStorage.getItem(SPLIT_KEY));
return v >= 20 && v <= 75 ? v : 40;
} catch {
return 40;
}
}
function setSplit(v) {
split.value = Math.min(75, Math.max(20, v));
}
function keepSplit() {
try {
localStorage.setItem(SPLIT_KEY, String(Math.round(split.value)));
} catch {
// As in readDraft.
}
}
function drag(e) {
e.preventDefault();
const handle = e.currentTarget;
const box = panes.value.getBoundingClientRect();
handle.setPointerCapture(e.pointerId);
const move = (ev) => setSplit(((ev.clientX - box.left) / box.width) * 100);
const up = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", up);
handle.removeEventListener("pointercancel", up);
keepSplit();
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", up);
handle.addEventListener("pointercancel", up);
}
function nudge(e) {
const step = { ArrowLeft: -2, ArrowRight: 2 }[e.key];
if (!step) return;
e.preventDefault();
setSplit(split.value + step);
keepSplit();
}
watch(() => props.name, load, { immediate: true });
</script>
<template>
<p v-if="loading" class="muted">Loading…</p>
<div v-else-if="error">
<p class="error">{{ error }}</p>
<RouterLink to="/">Back to the list</RouterLink>
</div>
<div v-else-if="problem && !admin" class="denied card">
<p>Solving in the browser is for the site's admin.</p>
<RouterLink :to="`/p/${name}`">Back to {{ title(problem.name) }}</RouterLink>
</div>
<div v-else-if="problem && info" ref="panes" class="solve" :style="{ '--left': `${split}%` }">
<aside class="left card">
<RouterLink :to="`/p/${problem.name}`" class="back">← Problem page</RouterLink>
<h1>{{ title(problem.name) }}</h1>
<div class="facts">
<span class="badge" :class="problem.status">{{ STATUS_LABELS[problem.status] }}</span>
<a v-if="problem.url" :href="problem.url" target="_blank" rel="noopener noreferrer">
{{ problem.source || "Problem statement" }} ↗
</a>
<span v-if="info.io" class="muted">File I/O: <code>{{ info.io }}.in</code></span>
<span v-if="info.leetcode" class="muted">LeetCode</span>
</div>
<div v-if="statementHtml" class="statement prose" v-html="statementHtml"></div>
<p v-else class="muted">
No statement saved. Add it under Edit details on the
<RouterLink :to="`/p/${problem.name}`">problem page</RouterLink>.
</p>
<section v-if="problem.testCases.length">
<h2>Tests</h2>
<details v-for="t in problem.testCases" :key="t.name" class="test">
<summary>Test {{ t.name }}</summary>
<div class="io">
<div>
<p class="filename muted">Input</p>
<CodeBlock :content="t.input.content" :truncated="t.input.truncated" />
</div>
<div>
<p class="filename muted">Expected output</p>
<CodeBlock v-if="t.output" :content="t.output.content" :truncated="t.output.truncated" />
<p v-else class="muted">Not saved.</p>
</div>
</div>
</details>
</section>
<section v-else-if="problem.sample">
<h2>Sample input</h2>
<CodeBlock :content="problem.sample.content" :truncated="problem.sample.truncated" />
</section>
</aside>
<div
class="split"
role="separator"
tabindex="0"
aria-orientation="vertical"
aria-label="Resize the panes"
aria-valuemin="20"
aria-valuemax="75"
:aria-valuenow="Math.round(split)"
@pointerdown="drag"
@keydown="nudge"
></div>
<div class="right">
<div class="toolbar">
<select aria-label="Language" :value="lang" :disabled="busy" @change="switchLang($event.target.value)">
<option v-for="l in info.languages" :key="l" :value="l">{{ LANG_LABELS[l] || l }}</option>
</select>
<button class="btn" type="button" :disabled="busy || !dirty" @click="reset">
Reset to {{ current.saved ? "saved" : "starter" }}
</button>
<span class="grow"></span>
<button
class="btn"
type="button"
:disabled="!canRun"
:title="`Run on the custom input (${MOD_KEY}+Enter)`"
@click="run('custom')"
>
{{ running === "custom" ? "Running…" : "Run" }}
</button>
<button
class="btn primary"
type="button"
:disabled="!canRun"
:title="`Run the saved tests (${MOD_KEY}+Shift+Enter)`"
@click="run('tests')"
>
{{ running === "tests" ? "Submitting…" : "Submit" }}
</button>
<button class="btn" type="button" :disabled="!canSave" :title="`Commit to the repo (${MOD_KEY}+S)`" @click="save">
{{ saving ? "Saving…" : "Save" }}
</button>
</div>
<div class="status" role="status">
<span :class="{ draft: dirty }">{{ codeStatus }}</span>
<span v-if="saving" class="muted">Committing to git…</span>
<span v-if="notice" class="done">{{ notice }}</span>
<span v-if="saveError" class="error">Save: {{ saveError }}</span>
<span class="grow"></span>
<span v-if="lintError" class="error" :title="lintError">Lint failed</span>
<span v-else-if="linted" class="lint">
<span v-if="lintSummary.errors" class="error">{{ lintSummary.errors }}</span>
<span v-if="lintSummary.errors && lintSummary.rest" class="muted"> · </span>
<span v-if="lintSummary.rest" class="warn">{{ lintSummary.rest }}</span>
<span v-if="!lintSummary.errors && !lintSummary.rest" class="muted">No lint issues</span>
</span>
</div>
<p v-if="!info.runner" class="muted note">
The code runner isn't configured (RUNNER_URL), so Run, Submit and lint are off. Save still works.
</p>
<CodeEditor
v-model="source"
class="code"
:lang="lang"
:diagnostics="diagnostics"
:label="`${LANG_LABELS[lang] || lang} solution`"
@run="run('custom')"
@submit="run('tests')"
@save="save"
/>
<RunResults v-model="customInput" class="out" :result="result" :running="running" :error="runError" />
</div>
</div>
</template>
<style scoped>
.solve {
height: 100%;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, var(--left)) 12px minmax(0, 1fr);
}
.left {
min-height: 0;
overflow: auto;
padding: 14px 18px 20px;
display: grid;
align-content: start;
gap: 16px;
}
.left > * {
min-width: 0;
}
.back {
font-size: 0.875rem;
color: var(--color-ink-muted);
text-decoration: none;
}
.back:hover {
color: var(--color-ink);
}
h1 {
font-size: 2.25rem;
margin: -8px 0 0;
overflow-wrap: anywhere;
}
h2 {
font-size: 1.4rem;
margin-bottom: 6px;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 16px;
font-size: 0.9rem;
margin-top: -8px;
}
.facts code {
font-family: var(--font-mono);
font-size: 0.85em;
}
.statement {
padding-top: 12px;
border-top: 1px solid var(--color-line-soft);
}
.test {
border: 1px solid var(--color-line-soft);
border-radius: 6px;
margin-bottom: 8px;
}
.test summary {
padding: 6px 12px;
cursor: pointer;
}
.io {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
padding: 0 12px 12px;
min-width: 0;
}
.io > div {
min-width: 0;
}
.filename {
font-family: var(--font-mono);
font-size: 0.8rem;
margin-bottom: 4px;
}
/* The divider: a line in the middle of a gap wide enough to grab. */
.split {
cursor: col-resize;
touch-action: none;
position: relative;
}
.split::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 5px;
width: 2px;
border-radius: 1px;
background: transparent;
}
.split:hover::after,
.split:focus-visible::after {
background: var(--color-line);
}
.right {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.toolbar select {
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink);
cursor: pointer;
}
.toolbar select:disabled {
opacity: 0.5;
cursor: default;
}
.grow {
flex: 1;
}
.status {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 14px;
font-size: 0.85rem;
color: var(--color-ink-muted);
}
.status .draft {
color: var(--color-solving);
}
.status .done {
color: var(--color-solved);
}
.status .warn {
color: var(--color-solving);
}
.note {
font-size: 0.85rem;
}
.code {
flex: 1 1 0;
min-height: 160px;
}
.out {
flex: 0 0 38%;
min-height: 170px;
}
.denied {
padding: 16px 20px;
display: grid;
gap: 8px;
justify-items: start;
}
/* A phone or a narrow window: the panes stack and the page scrolls. */
@media (max-width: 899px) {
.solve {
display: flex;
flex-direction: column;
gap: 16px;
height: auto;
}
.split {
display: none;
}
.left {
overflow: visible;
}
.code {
flex: none;
height: 60vh;
}
.out {
flex: none;
height: auto;
}
}
</style>
+34
View File
@@ -0,0 +1,34 @@
import os
import sys
# ----- FILE IO -----
# stdio("name") picks the mode from the directory it runs in, like template.rs:
# name.in exists -> read name.in, write name.out (USACO + the site's Run)
# name.in missing -> read stdin, write stdout (Codeforces submission)
# Like freopen in template.cpp, it points fds 0 and 1 at the files, so
# input(), print() and sys.stdin.buffer all follow without being swapped.
def stdio(name):
if os.path.exists(name + ".in"):
os.dup2(os.open(name + ".in", os.O_RDONLY), 0)
os.dup2(os.open(name + ".out", os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 1)
# ----- INPUT -----
# Slurps the whole input (call it after stdio), then hands out tokens:
# n = int(next(tok))
# a = [int(next(tok)) for _ in range(n)]
# s = next(tok).decode()
def tokens():
return iter(sys.stdin.buffer.read().split())
def main():
stdio("problem")
tok = tokens()
t = int(next(tok))
for _ in range(t):
pass
main()