- 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]>
437 lines
14 KiB
Go
437 lines
14 KiB
Go
// 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), the
|
|
// solve page's code editing and runs (run.go) and evaluations
|
|
// (evaluate.go), the library of concepts Claude explained (concept.go), and
|
|
// the Gitea webhook that tells the server to pull.
|
|
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"adam-french.co.uk/usaco-site/internal/auth"
|
|
"adam-french.co.uk/usaco-site/internal/explain"
|
|
"adam-french.co.uk/usaco-site/internal/index"
|
|
"adam-french.co.uk/usaco-site/internal/jobs"
|
|
"adam-french.co.uk/usaco-site/internal/repo"
|
|
"adam-french.co.uk/usaco-site/internal/usage"
|
|
)
|
|
|
|
// Repo is the part of repo.Repo the handlers use, so tests can fake it.
|
|
type Repo interface {
|
|
Mutate(ctx context.Context, message string, edit func(dir string) error) error
|
|
}
|
|
|
|
// Server holds the current index and what is needed to change it.
|
|
type Server struct {
|
|
Repo Repo
|
|
Checker auth.Checker
|
|
WebhookSecret string
|
|
// 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
|
|
// Statements reads a statement from the problem's judge; nil means the
|
|
// real judges.
|
|
Statements Fetcher
|
|
// LeetCode starts the daily question and pasted links; 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
|
|
// 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
|
|
|
|
// Jobs keeps the background jobs' records (internal/jobs); nil keeps
|
|
// them in memory, which the tests use.
|
|
Jobs *jobs.Registry
|
|
// Usage is the Claude cost ledger and monthly budget; nil tracks
|
|
// nothing and allows everything.
|
|
Usage *usage.Ledger
|
|
|
|
idx atomic.Pointer[index.Index]
|
|
|
|
jobsOnce sync.Once
|
|
// Separate kinds, so a review, an explanation and an evaluation of one
|
|
// problem can run at the same time. New concepts are keyed by a job id
|
|
// (the slug is Claude's to pick), rewrites by slug.
|
|
explainJobs, reviewJobs, evalJobs, newConceptJobs, conceptJobs *jobs.Kind
|
|
}
|
|
|
|
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
|
|
// Reload) under its lock after every sync and edit.
|
|
func (s *Server) SetIndex(idx *index.Index) { s.idx.Store(idx) }
|
|
|
|
// Reload rebuilds the index from dir. It has repo.Repo's onChange signature.
|
|
func (s *Server) Reload(dir string) error {
|
|
idx, err := index.Build(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.SetIndex(idx)
|
|
log.Printf("[index] %d problems at %.12s", len(idx.Problems), idx.Head)
|
|
return nil
|
|
}
|
|
|
|
// Index is the current snapshot; nil until the first sync has finished.
|
|
func (s *Server) Index() *index.Index { return s.idx.Load() }
|
|
|
|
// Routes registers everything under api.
|
|
func (s *Server) Routes(api *gin.RouterGroup) {
|
|
s.initJobs()
|
|
// SameOrigin first, so a cross-site request is refused without asking
|
|
// the site backend about its cookies.
|
|
admin := api.Group("", auth.SameOrigin(), auth.Require(s.Checker))
|
|
|
|
api.GET("/health", s.health)
|
|
api.GET("/me", s.me)
|
|
api.GET("/problems", s.list)
|
|
api.GET("/problems/:name", s.get)
|
|
admin.PUT("/problems/:name/meta", s.updateMeta)
|
|
admin.POST("/problems/:name/status", s.setStatus)
|
|
admin.GET("/problems/:name/statement/fetch", s.fetchStatement)
|
|
admin.POST("/problems/:name/explain", s.startExplain)
|
|
admin.GET("/problems/:name/explain", s.explainStatus)
|
|
admin.POST("/problems/:name/review", s.startReview)
|
|
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)
|
|
admin.POST("/problems/:name/evaluate", s.startEvaluate)
|
|
admin.GET("/problems/:name/evaluate", s.evaluateStatus)
|
|
admin.POST("/leetcode/daily", s.startDaily)
|
|
admin.POST("/leetcode/import", s.startImport)
|
|
api.GET("/concepts", s.listConcepts)
|
|
api.GET("/concepts/:slug", s.getConcept)
|
|
admin.POST("/concepts", s.startConcept)
|
|
// Not under /concepts/, where "jobs" would be a slug.
|
|
admin.GET("/concept-jobs/:id", s.newConceptStatus)
|
|
admin.POST("/concepts/:slug/explain", s.rewriteConcept)
|
|
admin.GET("/concepts/:slug/explain", s.rewriteStatus)
|
|
admin.DELETE("/concepts/:slug", s.deleteConcept)
|
|
admin.POST("/jobs/:kind/:key/save", s.retrySave)
|
|
admin.GET("/usage", s.usage)
|
|
api.POST("/hooks/gitea", s.webhook)
|
|
}
|
|
|
|
func (s *Server) health(ctx *gin.Context) {
|
|
idx := s.Index()
|
|
if idx == nil {
|
|
ctx.JSON(http.StatusServiceUnavailable, gin.H{"status": "repository not loaded yet"})
|
|
return
|
|
}
|
|
ctx.JSON(http.StatusOK, gin.H{"status": "ok", "head": idx.Head})
|
|
}
|
|
|
|
func (s *Server) me(ctx *gin.Context) {
|
|
ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx)})
|
|
}
|
|
|
|
// visible says whether a problem may be shown to this caller: solved ones
|
|
// to anyone, the rest only to the admin.
|
|
func visible(p *index.Problem, admin bool) bool {
|
|
return admin || p.Status == index.Solved
|
|
}
|
|
|
|
// isAdmin asks the checker. auth.Forward answers a request with no cookies
|
|
// (nearly every public visitor) without asking the site backend.
|
|
func (s *Server) isAdmin(ctx *gin.Context) bool {
|
|
return s.Checker.IsAdmin(ctx.Writer, ctx.Request)
|
|
}
|
|
|
|
func (s *Server) list(ctx *gin.Context) {
|
|
idx := s.Index()
|
|
if idx == nil {
|
|
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
|
|
return
|
|
}
|
|
admin := s.isAdmin(ctx)
|
|
out := []index.Summary{}
|
|
for _, p := range idx.Problems {
|
|
if visible(p, admin) {
|
|
sum := p.Summary
|
|
if !admin {
|
|
sum.ReviewCount = 0
|
|
}
|
|
out = append(out, sum)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
|
ctx.JSON(http.StatusOK, gin.H{"head": idx.Head, "admin": admin, "problems": out})
|
|
}
|
|
|
|
// The CLI's names are slugs. Checking the shape before any lookup keeps
|
|
// anything path-like ("..", "a/b") away from the filesystem.
|
|
var validName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
|
|
|
|
// lookup finds a problem the caller may see. A problem the caller may not
|
|
// see is a 404 like a missing one, so its existence does not leak.
|
|
func (s *Server) lookup(ctx *gin.Context, admin bool) (*index.Problem, bool) {
|
|
name := ctx.Param("name")
|
|
idx := s.Index()
|
|
if idx == nil {
|
|
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
|
|
return nil, false
|
|
}
|
|
if !validName.MatchString(name) {
|
|
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
|
|
return nil, false
|
|
}
|
|
p, ok := idx.Problems[name]
|
|
if !ok || !visible(p, admin) {
|
|
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
|
|
return nil, false
|
|
}
|
|
return p, true
|
|
}
|
|
|
|
func (s *Server) get(ctx *gin.Context) {
|
|
admin := s.isAdmin(ctx)
|
|
p, ok := s.lookup(ctx, admin)
|
|
if !ok {
|
|
return
|
|
}
|
|
// The statement is the judge's text, kept for the admin and for Claude;
|
|
// the public page links to the judge instead. Reviews are a transcript
|
|
// of the admin talking. The index is shared, so this blanks a copy.
|
|
if !admin && (p.Statement != "" || len(p.Reviews) > 0) {
|
|
c := *p
|
|
c.Statement = ""
|
|
c.Reviews, c.ReviewCount = []index.Review{}, 0
|
|
p = &c
|
|
}
|
|
ctx.JSON(http.StatusOK, p)
|
|
}
|
|
|
|
// requestError is an edit that cannot be made, with the status to send.
|
|
type requestError struct {
|
|
status int
|
|
msg string
|
|
}
|
|
|
|
func (e *requestError) Error() string { return e.msg }
|
|
|
|
// mutate runs an edit through the repo and answers with the problem as it
|
|
// is afterwards (under its possibly new status).
|
|
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()
|
|
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 errors.As(err, &re):
|
|
ctx.JSON(re.status, gin.H{"error": re.msg})
|
|
case errors.Is(err, repo.ErrRejected):
|
|
ctx.JSON(http.StatusConflict, gin.H{"error": "the repository changed while saving; try again"})
|
|
default:
|
|
log.Printf("[edit] %s: %v", message, err)
|
|
ctx.JSON(http.StatusBadGateway, gin.H{"error": "could not save to git"})
|
|
}
|
|
}
|
|
|
|
// findOnDisk locates a problem in the freshly synced clone. Edits decide
|
|
// from the disk, not the index, because Mutate may replay them on a newer
|
|
// tip than the one the index was built from.
|
|
func findOnDisk(dir, name string) (status string, err error) {
|
|
for _, st := range index.Statuses {
|
|
if info, err := os.Stat(filepath.Join(dir, st, name)); err == nil && info.IsDir() {
|
|
return st, nil
|
|
}
|
|
}
|
|
return "", &requestError{http.StatusNotFound, "no such problem"}
|
|
}
|
|
|
|
type metaBody struct {
|
|
URL *string `json:"url"`
|
|
Notes *string `json:"notes"`
|
|
Statement *string `json:"statement"`
|
|
}
|
|
|
|
const maxNotes = 64 << 10
|
|
|
|
func (s *Server) updateMeta(ctx *gin.Context) {
|
|
p, ok := s.lookup(ctx, true)
|
|
if !ok {
|
|
return
|
|
}
|
|
var body metaBody
|
|
if err := ctx.ShouldBindJSON(&body); err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
|
return
|
|
}
|
|
if body.URL != nil {
|
|
u := strings.TrimSpace(*body.URL)
|
|
if u != "" {
|
|
parsed, err := url.Parse(u)
|
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || len(u) > 2048 {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an http(s) link"})
|
|
return
|
|
}
|
|
}
|
|
body.URL = &u
|
|
}
|
|
if body.Notes != nil && len(*body.Notes) > maxNotes {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "notes are too long"})
|
|
return
|
|
}
|
|
if body.Statement != nil && len(*body.Statement) > maxNotes {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the statement is too long"})
|
|
return
|
|
}
|
|
|
|
name := p.Name
|
|
s.mutate(ctx, name, "Update "+name, func(dir string) error {
|
|
status, err := findOnDisk(dir, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pdir := filepath.Join(dir, status, name)
|
|
if body.URL != nil {
|
|
// Same format `usaco new --url` writes: the link and a newline.
|
|
if err := writeOrRemove(filepath.Join(pdir, ".url"), *body.URL); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if body.Notes != nil {
|
|
if err := writeOrRemove(filepath.Join(pdir, "notes.md"), *body.Notes); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if body.Statement != nil {
|
|
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), *body.Statement); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// writeOrRemove writes content plus a trailing newline, or removes the file
|
|
// when content is blank, so clearing a field leaves no empty file behind.
|
|
func writeOrRemove(path, content string) error {
|
|
content = strings.TrimRight(content, " \t\r\n")
|
|
if content == "" {
|
|
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
return os.WriteFile(path, []byte(content+"\n"), 0o644)
|
|
}
|
|
|
|
type statusBody struct {
|
|
To string `json:"to"`
|
|
}
|
|
|
|
// The commit subjects match the CLI's: `usaco done` commits "Solve <name>".
|
|
var statusVerb = map[string]string{
|
|
index.Solved: "Solve",
|
|
index.Skipped: "Skip",
|
|
index.Solving: "Reopen",
|
|
}
|
|
|
|
func (s *Server) setStatus(ctx *gin.Context) {
|
|
p, ok := s.lookup(ctx, true)
|
|
if !ok {
|
|
return
|
|
}
|
|
var body statusBody
|
|
if err := ctx.ShouldBindJSON(&body); err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
|
return
|
|
}
|
|
verb, ok := statusVerb[body.To]
|
|
if !ok {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "to must be solving, solved or skipped"})
|
|
return
|
|
}
|
|
name := p.Name
|
|
s.mutate(ctx, name, verb+" "+name, func(dir string) error {
|
|
from, err := findOnDisk(dir, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if from == body.To {
|
|
return nil
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(dir, body.To), 0o755); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(filepath.Join(dir, from, name), filepath.Join(dir, body.To, name))
|
|
})
|
|
}
|
|
|
|
// webhook accepts Gitea's push hook. Gitea signs the body with the shared
|
|
// secret (HMAC-SHA256, hex, in X-Gitea-Signature). The body itself is not
|
|
// read beyond that: any push to the repo is a reason to pull.
|
|
func (s *Server) webhook(ctx *gin.Context) {
|
|
if s.WebhookSecret == "" {
|
|
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "webhook not configured"})
|
|
return
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(ctx.Request.Body, 5<<20))
|
|
if err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unreadable body"})
|
|
return
|
|
}
|
|
if !validSignature(s.WebhookSecret, body, ctx.GetHeader("X-Gitea-Signature")) {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "bad signature"})
|
|
return
|
|
}
|
|
s.Pull()
|
|
ctx.JSON(http.StatusAccepted, gin.H{"status": "pull queued"})
|
|
}
|
|
|
|
func validSignature(secret string, body []byte, sig string) bool {
|
|
got, err := hex.DecodeString(strings.TrimPrefix(sig, "sha256="))
|
|
if err != nil || len(got) == 0 {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write(body)
|
|
return hmac.Equal(got, mac.Sum(nil))
|
|
}
|