Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6b82588b1 | ||
|
|
af070ffcf9 |
+4
-1
@@ -14,6 +14,9 @@
|
||||
# The runtime runs as uid 1000, not root. DATA_DIR (/data) must be writable by
|
||||
# it: with a bind mount, `chown 1000 <dir>` on the host. git is the server's
|
||||
# storage layer (internal/repo shells out to it); wget is for the healthcheck.
|
||||
# python3 runs the clone's lib/leetcode.py, the CLI's LeetCode importer, for
|
||||
# the "Today's LeetCode" button (internal/leetcode). It never runs solutions:
|
||||
# those go to the runner (Dockerfile.runner).
|
||||
# =============================================================================
|
||||
FROM node:22-alpine AS web
|
||||
WORKDIR /web
|
||||
@@ -33,7 +36,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/usacosite ./cmd/usacosite
|
||||
|
||||
FROM alpine:3.22
|
||||
RUN apk add --no-cache ca-certificates git wget \
|
||||
RUN apk add --no-cache ca-certificates git wget python3 \
|
||||
&& adduser -D -H -u 1000 app \
|
||||
&& mkdir /data && chown app /data
|
||||
COPY --from=build /out/usacosite /app/usacosite
|
||||
|
||||
+18
-1
@@ -13,6 +13,17 @@
|
||||
# ruff Python lint (optional)
|
||||
# tini PID 1; see below
|
||||
# A missing linter only means less lint; see internal/runner.
|
||||
# Alpine 3.24 for clang-tidy 22, which walks far less of the
|
||||
# system headers than 3.22's clang-tidy 20: about 4x faster on
|
||||
# the same file, which on the production host was the
|
||||
# difference between a 30s lint and a usable one.
|
||||
#
|
||||
# It also precompiles <bits/stdc++.h>, which every solution
|
||||
# includes, into /opt/pch (internal/runner/pch.go): a .gch for
|
||||
# g++ and a .pch for clang-tidy, built with the flags the runner
|
||||
# passes (-std=c++17 -O2 -DLOCAL), since both compilers reject
|
||||
# a header built differently. A build drops from about 4s to
|
||||
# 0.6s on the production host.
|
||||
#
|
||||
# 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,
|
||||
@@ -45,9 +56,15 @@ 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
|
||||
FROM alpine:3.24
|
||||
RUN apk add --no-cache g++ musl-dev python3 clang-extra-tools ruff tini \
|
||||
&& adduser -D -H -u 1000 app
|
||||
RUN header=$(echo '#include <bits/stdc++.h>' | g++ -std=c++17 -x c++ -E -H - 2>&1 >/dev/null \
|
||||
| grep -m1 'bits/stdc++\.h$' | sed 's/^\.* //') \
|
||||
&& test -f "$header" \
|
||||
&& mkdir -p /opt/pch/bits \
|
||||
&& g++ -std=c++17 -O2 -DLOCAL -x c++-header "$header" -o /opt/pch/bits/stdc++.h.gch \
|
||||
&& clang++ -std=c++17 -DLOCAL -x c++-header "$header" -o /opt/pch/stdc++.pch
|
||||
COPY --from=build /out/usacorunner /app/usacorunner
|
||||
USER app
|
||||
ENV TMPDIR=/tmp
|
||||
|
||||
+3
-1
@@ -52,6 +52,7 @@ internal/explain/ the explanation prompt and schema, explain.md rendering, the
|
||||
internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/filler metrics
|
||||
internal/review/ the review prompt and schema, reviews/<id>.md rendering
|
||||
internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback
|
||||
internal/leetcode/ today's daily question, imported by running the clone's lib/leetcode.py
|
||||
internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page)
|
||||
web/ Vue 3 + Vite SPA, built for base /usaco/
|
||||
```
|
||||
@@ -79,6 +80,7 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
|
||||
| `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/leetcode/daily` | admin | imports today's LeetCode daily question into `solving/` with the CLI's `lib/leetcode.py` and commits it as "Start <slug>", or finds it if it is already a problem; answers `{name, created}`. 502 if LeetCode or the import fails |
|
||||
| `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull |
|
||||
| `GET /usaco/api/health` | open | 200 once the clone is indexed |
|
||||
|
||||
@@ -176,7 +178,7 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
|
||||
|
||||
- **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.
|
||||
- **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. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22).
|
||||
|
||||
## Things that are easy to get wrong
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/leetcode"
|
||||
)
|
||||
|
||||
// LeetCode is the part of leetcode.Importer the handlers use, so tests can
|
||||
// fake LeetCode and the import script.
|
||||
type LeetCode interface {
|
||||
Daily(ctx context.Context) (string, error)
|
||||
Import(ctx context.Context, root, slug string) error
|
||||
}
|
||||
|
||||
func (s *Server) leetcode() LeetCode {
|
||||
if s.LeetCode != nil {
|
||||
return s.LeetCode
|
||||
}
|
||||
return &leetcode.Importer{}
|
||||
}
|
||||
|
||||
// startDaily is `usaco daily`: it imports today's LeetCode daily question
|
||||
// into solving/ and commits it, and answers its name for the page to open.
|
||||
// A daily question already in the repo (started yesterday from the CLI, or
|
||||
// solved months ago) is only named, never imported again.
|
||||
func (s *Server) startDaily(ctx *gin.Context) {
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
lc := s.leetcode()
|
||||
slug, err := lc.Daily(c)
|
||||
if err != nil {
|
||||
log.Printf("[daily] %v", err)
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// The slug becomes a directory name.
|
||||
if !validName.MatchString(slug) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "LeetCode named the daily question " + slug + ", which is not a usable name"})
|
||||
return
|
||||
}
|
||||
if idx := s.Index(); idx != nil {
|
||||
if _, ok := idx.Problems[slug]; ok {
|
||||
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": false})
|
||||
return
|
||||
}
|
||||
}
|
||||
created := false
|
||||
err = s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
|
||||
if _, err := findOnDisk(dir, slug); err == nil {
|
||||
created = false
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
if err := lc.Import(c, dir, slug); err != nil {
|
||||
return &requestError{http.StatusBadGateway, err.Error()}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
editFailed(ctx, "Start "+slug, err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": created})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeLeetCode names slug as the daily question, and imports it by writing a
|
||||
// main.cpp, as lib/leetcode.py would (much more fully).
|
||||
type fakeLeetCode struct {
|
||||
slug string
|
||||
err error
|
||||
imports int
|
||||
}
|
||||
|
||||
func (f *fakeLeetCode) Daily(context.Context) (string, error) { return f.slug, nil }
|
||||
|
||||
func (f *fakeLeetCode) Import(_ context.Context, root, slug string) error {
|
||||
f.imports++
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
dir := filepath.Join(root, "solving", slug)
|
||||
os.MkdirAll(dir, 0o755)
|
||||
return os.WriteFile(filepath.Join(dir, "main.cpp"), []byte("class Solution {};\n"), 0o644)
|
||||
}
|
||||
|
||||
type dailyReply struct {
|
||||
Name string `json:"name"`
|
||||
Created bool `json:"created"`
|
||||
}
|
||||
|
||||
func TestDailyImports(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
lc := &fakeLeetCode{slug: "two-sum"}
|
||||
repo.srv.LeetCode = lc
|
||||
|
||||
if rec := do(r, "POST", "/usaco/api/leetcode/daily", "", false); rec.Code != 401 {
|
||||
t.Fatalf("non-admin = %d, want 401", rec.Code)
|
||||
}
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
|
||||
var got dailyReply
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if rec.Code != 200 || got != (dailyReply{"two-sum", true}) {
|
||||
t.Fatalf("daily = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if len(repo.msg) != 1 || repo.msg[0] != "Start two-sum" {
|
||||
t.Fatalf("commits = %v", repo.msg)
|
||||
}
|
||||
if _, ok := repo.srv.Index().Problems["two-sum"]; !ok {
|
||||
t.Fatal("two-sum is not in the index after the import")
|
||||
}
|
||||
|
||||
// The second press only names it.
|
||||
rec = do(r, "POST", "/usaco/api/leetcode/daily", "", true)
|
||||
got = dailyReply{}
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if rec.Code != 200 || got != (dailyReply{"two-sum", false}) || lc.imports != 1 {
|
||||
t.Fatalf("second daily = %d %s after %d imports", rec.Code, rec.Body, lc.imports)
|
||||
}
|
||||
}
|
||||
|
||||
// A daily question that is already a problem, whatever its status, is not
|
||||
// imported over.
|
||||
func TestDailyExisting(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
lc := &fakeLeetCode{slug: "moocast"}
|
||||
repo.srv.LeetCode = lc
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
|
||||
if rec.Code != 200 || lc.imports != 0 || len(repo.msg) != 0 {
|
||||
t.Fatalf("daily = %d %s, %d imports, commits %v", rec.Code, rec.Body, lc.imports, repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyImportFails(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
repo.srv.LeetCode = &fakeLeetCode{slug: "paid-only", err: errors.New("LeetCode returned no statement for 'paid-only' (a premium problem?)")}
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
|
||||
if rec.Code != 502 || len(repo.msg) != 0 {
|
||||
t.Fatalf("daily = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,9 @@ type Server struct {
|
||||
// Statements reads a statement from the problem's judge; nil means the
|
||||
// real judges.
|
||||
Statements Fetcher
|
||||
// LeetCode starts the daily question; nil means the real API and the
|
||||
// clone's lib/leetcode.py.
|
||||
LeetCode LeetCode
|
||||
// Transcriber turns review recordings into text; nil when
|
||||
// TRANSCRIBE_API_KEY is not set, which turns reviews off.
|
||||
Transcriber Transcriber
|
||||
@@ -108,6 +111,7 @@ func (s *Server) Routes(api *gin.RouterGroup) {
|
||||
admin.PUT("/problems/:name/code", s.saveCode)
|
||||
admin.POST("/problems/:name/run", s.run)
|
||||
admin.POST("/problems/:name/lint", s.lint)
|
||||
admin.POST("/leetcode/daily", s.startDaily)
|
||||
api.POST("/hooks/gitea", s.webhook)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// Package leetcode starts LeetCode problems from the site the way `usaco
|
||||
// daily` does from the CLI. The import itself is the CLI's: lib/leetcode.py
|
||||
// in the clone writes problem.md, main.cpp, the generated driver.h and the
|
||||
// examples as tests. Rewriting its driver generator in Go would leave two
|
||||
// copies to drift apart, so the site image carries python3 to run it.
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Importer asks LeetCode for the daily question and runs the CLI's importer.
|
||||
// The zero value talks to the real API with python3 from PATH; tests point
|
||||
// API at an httptest server.
|
||||
type Importer struct {
|
||||
Client *http.Client
|
||||
API string // default https://leetcode.com/graphql
|
||||
Python string // default python3
|
||||
}
|
||||
|
||||
// Daily is the slug of today's daily question.
|
||||
func (i *Importer) Daily(ctx context.Context) (string, error) {
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"query": "query { activeDailyCodingChallengeQuestion { question { titleSlug } } }",
|
||||
})
|
||||
api := i.API
|
||||
if api == "" {
|
||||
api = "https://leetcode.com/graphql"
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Referer", "https://leetcode.com")
|
||||
client := i.Client
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not reach LeetCode")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("LeetCode answered %s", resp.Status)
|
||||
}
|
||||
var out struct {
|
||||
Data struct {
|
||||
Daily *struct {
|
||||
Question struct {
|
||||
Slug string `json:"titleSlug"`
|
||||
} `json:"question"`
|
||||
} `json:"activeDailyCodingChallengeQuestion"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil {
|
||||
return "", fmt.Errorf("LeetCode answered with something other than JSON")
|
||||
}
|
||||
if out.Data.Daily == nil || out.Data.Daily.Question.Slug == "" {
|
||||
return "", fmt.Errorf("LeetCode named no daily question")
|
||||
}
|
||||
return out.Data.Daily.Question.Slug, nil
|
||||
}
|
||||
|
||||
// Import runs `lib/leetcode.py root slug` in the clone at root, which
|
||||
// creates solving/<slug>. The script reports a failure as "Error: ..." on
|
||||
// stderr, which is what the admin is shown.
|
||||
func (i *Importer) Import(ctx context.Context, root, slug string) error {
|
||||
python := i.Python
|
||||
if python == "" {
|
||||
python = "python3"
|
||||
}
|
||||
var stderr bytes.Buffer
|
||||
cmd := exec.CommandContext(ctx, python, "-I", filepath.Join(root, "lib", "leetcode.py"), root, slug)
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
for _, line := range strings.Split(stderr.String(), "\n") {
|
||||
if msg, ok := strings.CutPrefix(line, "Error: "); ok {
|
||||
return errors.New(msg)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("the LeetCode import failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDaily(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":{"question":{"titleSlug":"two-sum"}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
slug, err := (&Importer{API: srv.URL}).Daily(context.Background())
|
||||
if err != nil || slug != "two-sum" {
|
||||
t.Fatalf("Daily = %q, %v; want two-sum", slug, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyMissing(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":null}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := (&Importer{API: srv.URL}).Daily(context.Background()); err == nil {
|
||||
t.Fatal("Daily with no question succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// The script's own "Error: ..." line is the message, not the exit status.
|
||||
func TestImportError(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("no python3")
|
||||
}
|
||||
root := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(root, "lib"), 0o755)
|
||||
script := "import sys\nprint('Error: LeetCode has no problem ' + repr(sys.argv[2]), file=sys.stderr)\nsys.exit(1)\n"
|
||||
os.WriteFile(filepath.Join(root, "lib", "leetcode.py"), []byte(script), 0o644)
|
||||
err := (&Importer{}).Import(context.Background(), root, "nope")
|
||||
if err == nil || !strings.Contains(err.Error(), "LeetCode has no problem 'nope'") {
|
||||
t.Fatalf("Import = %v, want the script's message", err)
|
||||
}
|
||||
}
|
||||
@@ -128,12 +128,14 @@ func runTool(ctx context.Context, ws *workspace, name string, args []string, std
|
||||
// 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.
|
||||
// column as it does in the editor. -O2 as in the build: the precompiled
|
||||
// header only matches the same optimization level, and some warnings
|
||||
// (maybe-uninitialized) only come with it.
|
||||
func lintGCC(ctx context.Context, ws *workspace) []Diagnostic {
|
||||
out := runTool(ctx, ws, "g++", []string{
|
||||
out := runTool(ctx, ws, "g++", withGCCPCH([]string{
|
||||
"g++", "-fsyntax-only", "-fdiagnostics-plain-output", "-fdiagnostics-column-unit=byte",
|
||||
"-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "main.cpp",
|
||||
}, "")
|
||||
"-O2", "-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "main.cpp",
|
||||
}), "")
|
||||
return parseGCC(out)
|
||||
}
|
||||
|
||||
@@ -185,10 +187,10 @@ func parseGCC(out string) []Diagnostic {
|
||||
// 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{
|
||||
out := runTool(ctx, ws, "clang-tidy", append([]string{
|
||||
"clang-tidy", "main.cpp", "--quiet", "--config=" + tidyConfig,
|
||||
"--", "-std=c++17", "-DLOCAL", "-I.",
|
||||
}, "")
|
||||
}, tidyPCH()...), "")
|
||||
main := filepath.Join(ws.work, "main.cpp")
|
||||
paths := map[string]bool{"main.cpp": true, main: true}
|
||||
if real, err := filepath.EvalSymlinks(main); err == nil {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Every solution includes <bits/stdc++.h>, and parsing it is most of the
|
||||
// work of a build or a lint: on the production host (2 slow cores) a
|
||||
// trivial program took 3.9s to build without a precompiled header and 0.6s
|
||||
// with one. Dockerfile.runner builds both kinds into pchDir; without them
|
||||
// (go test, a run outside the image) the same commands just take longer.
|
||||
var pchDir = func() string {
|
||||
if d := os.Getenv("PCH_DIR"); d != "" {
|
||||
return d
|
||||
}
|
||||
return "/opt/pch"
|
||||
}()
|
||||
|
||||
// gccPCH puts pchDir/bits/stdc++.h.gch ahead of the real header. g++ checks
|
||||
// that it was built with matching options (-std=c++17, -O2, LOCAL) and
|
||||
// silently reads the real header when it was not, so it can only be slow,
|
||||
// never wrong.
|
||||
func gccPCH() []string {
|
||||
if _, err := os.Stat(filepath.Join(pchDir, "bits", "stdc++.h.gch")); err != nil {
|
||||
return nil
|
||||
}
|
||||
return []string{"-I" + pchDir}
|
||||
}
|
||||
|
||||
// tidyPCH preloads clang's precompiled bits/stdc++.h; main.cpp's own
|
||||
// #include of it is then a no-op behind its include guard. Unlike g++,
|
||||
// clang refuses a mismatched one, so the image builds it with the same
|
||||
// -std and -DLOCAL that lintTidy passes.
|
||||
func tidyPCH() []string {
|
||||
pch := filepath.Join(pchDir, "stdc++.pch")
|
||||
if _, err := os.Stat(pch); err != nil {
|
||||
return nil
|
||||
}
|
||||
return []string{"-include-pch", pch}
|
||||
}
|
||||
|
||||
// withGCCPCH is a g++ command line with gccPCH's -I after the program name.
|
||||
func withGCCPCH(args []string) []string {
|
||||
pch := gccPCH()
|
||||
if len(pch) == 0 {
|
||||
return args
|
||||
}
|
||||
out := append([]string{args[0]}, pch...)
|
||||
return append(out, args[1:]...)
|
||||
}
|
||||
@@ -114,9 +114,13 @@ func ioName(io string) string {
|
||||
|
||||
func compile(ctx context.Context, ws *workspace, lang language) Compile {
|
||||
out := ws.capture("compile.txt")
|
||||
args := lang.compile
|
||||
if args[0] == "g++" {
|
||||
args = withGCCPCH(args)
|
||||
}
|
||||
o := proc{
|
||||
dir: ws.work,
|
||||
args: lang.compile,
|
||||
args: args,
|
||||
stdout: out,
|
||||
stderr: out,
|
||||
limits: limits{cpuSec: int(compileTimeout / time.Second), memoryKB: compileMemoryKB, fileBlocks: fileBlocks},
|
||||
|
||||
@@ -60,3 +60,6 @@ export const runCode = (name, body) => request("POST", `/problems/${encodeURICom
|
||||
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);
|
||||
// Imports today's LeetCode daily question (or finds it, if it is already a
|
||||
// problem) and answers { name, created }. It takes a few seconds.
|
||||
export const startDaily = () => request("POST", "/leetcode/daily");
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import { listProblems } from "@/api";
|
||||
import { listProblems, startDaily } from "@/api";
|
||||
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
|
||||
|
||||
const route = useRoute();
|
||||
@@ -18,6 +18,22 @@ const admin = ref(false);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
|
||||
// "Today's LeetCode" imports the daily question as `usaco daily` would and
|
||||
// opens it on the solve page; one already in the repo is just opened.
|
||||
const starting = ref(false);
|
||||
const dailyError = ref("");
|
||||
async function openDaily() {
|
||||
starting.value = true;
|
||||
dailyError.value = "";
|
||||
try {
|
||||
const { name } = await startDaily();
|
||||
router.push({ name: "solve", params: { name } });
|
||||
} catch (e) {
|
||||
dailyError.value = e.message;
|
||||
starting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const status = computed({
|
||||
get: () => route.query.status || "all",
|
||||
set: (v) => router.replace({ query: { ...route.query, status: v === "all" ? undefined : v } }),
|
||||
@@ -110,7 +126,11 @@ const groups = computed(() => {
|
||||
<option value="recent">Most recent</option>
|
||||
<option value="name">Name</option>
|
||||
</select>
|
||||
<button v-if="admin" class="btn primary" :disabled="starting" @click="openDaily">
|
||||
{{ starting ? "Fetching today's problem…" : "Today's LeetCode" }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="dailyError" class="error daily-error">{{ dailyError }}</p>
|
||||
|
||||
<p v-if="loading" class="muted">Loading…</p>
|
||||
<p v-else-if="error" class="error">{{ error }}</p>
|
||||
@@ -151,6 +171,9 @@ const groups = computed(() => {
|
||||
.intro {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.daily-error {
|
||||
margin: -8px 0 16px;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
Reference in New Issue
Block a user