Files
usaco/site/internal/handlers/evaluate.go
T
adamfandClaude Opus 5.5 cae5ec8e5a
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s
Keep site jobs across restarts, meter Claude spend, harden admin routes
- internal/jobs replaces explain.Jobs: one registry for every kind of
  background job, with records in DATA_DIR/jobs. A job's draft is written
  before its commit, so a failed commit can be saved again (POST
  /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without
  paying Claude twice.
- Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for
  running ones while still serving the pages that poll them.
- internal/usage records every Claude call's tokens and estimated cost in
  DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a
  month reaches it. The stats page shows the admin the spend.
- auth.SameOrigin refuses cross-origin writes to admin routes.
- The LeetCode importer runs the clone's script without the server's
  secrets in its environment.
- A sync that leaves HEAD where it was skips the re-index.
- docs_test.go checks README's route table against the routes, and the CLI
  page against the root README's commands.
- The repo is going private: Gitea links on the site are admin-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:10:01 +01:00

115 lines
3.7 KiB
Go

package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/runner"
)
// The saved tests run first and Claude takes a minute or two after.
const evaluateTimeout = 10 * time.Minute
// startEvaluate starts judging the editor's source and answers at once; the
// page polls evaluateStatus, whose result is the evaluation. Nothing is
// committed: the source is a draft, and the answer is about this version of
// it only.
func (s *Server) startEvaluate(ctx *gin.Context) {
if !s.claudeReady(ctx) {
return
}
body, p, l, ok := s.readCode(ctx)
if !ok {
return
}
if strings.TrimSpace(body.Source) == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
if strings.TrimSpace(p.Statement) == "" && p.URL == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"})
return
}
in := evaluate.Input{
Name: p.Name, Statement: p.Statement, Examples: examples(p),
Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note,
}
link := p.URL
if startJob(ctx, s.evalJobs, p.Name, "a solution is already being evaluated", func() (any, error) { return s.evaluate(in, link, l) }) {
ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name))
}
}
func (s *Server) evaluateStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.evalJobs.Get(p.Name))
}
}
// evaluate is one job. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) evaluate(in evaluate.Input, link string, l *layout) (*evaluate.Evaluation, error) {
ctx, cancel := context.WithTimeout(context.Background(), evaluateTimeout)
defer cancel()
name := in.Name
// A fetched statement is not saved: that would be the only commit an
// evaluation makes. Explain or Edit details keep one.
if _, err := s.ensureStatement(ctx, "evaluate", name, &in.Statement, link); err != nil {
return nil, err
}
in.Run, in.RunNote = s.evaluationRun(ctx, name, in.Lang, in.Source, l)
ev, err := evaluate.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[evaluate] %s: %s: %v", name, f.Msg, f.Err)
return nil, f
}
log.Printf("[evaluate] %s: %v", name, err)
return nil, errors.New("the evaluation could not be written")
}
return ev, nil
}
// evaluationRun is Submit's run, for Claude to read. A run that cannot
// happen costs the evaluation its test verdicts, not the evaluation: the
// note says why, and goes to Claude in their place.
func (s *Server) evaluationRun(ctx context.Context, name, lang, source string, l *layout) (*runner.RunResponse, string) {
if s.Runner == nil {
return nil, "The tests were not run: the code runner is not configured."
}
tests, err := readRunTests(l)
if err != nil {
log.Printf("[evaluate] %s: reading the tests: %v", name, err)
return nil, "The tests were not run: they could not be read."
}
files, err := s.headers(l, lang)
if err != nil {
log.Printf("[evaluate] %s: reading the headers: %v", name, err)
return nil, "The tests were not run: the headers could not be read."
}
c, cancel := context.WithTimeout(ctx, runTimeout)
defer cancel()
res, err := s.Runner.Run(c, runner.RunRequest{Lang: lang, Source: source, Files: files, IO: l.io, Tests: tests})
if err != nil {
log.Printf("[evaluate] %s: running the tests: %v", name, err)
return nil, "The tests were not run: the code runner failed."
}
return &res, ""
}