Keep site jobs across restarts, meter Claude spend, harden admin routes
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s

- 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]>
This commit is contained in:
2026-10-23 22:10:01 +01:00
co-authored by Claude Opus 5.5
parent 7638d88570
commit cae5ec8e5a
42 changed files with 1849 additions and 264 deletions
+57 -29
View File
@@ -2,6 +2,7 @@ package handlers
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
@@ -78,8 +79,7 @@ const maxConceptCode = 32 << 10
// choose, so the job is keyed by an id of its own, which the page polls
// until the result names the slug to open.
func (s *Server) startConcept(ctx *gin.Context) {
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
idx := s.Index()
@@ -110,11 +110,9 @@ func (s *Server) startConcept(ctx *gin.Context) {
in := concept.Input{Topic: topic, Code: body.Code, Existing: conceptRefs(idx, "")}
// Microseconds, so two requests in one second are two jobs.
id := time.Now().UTC().Format("2006-01-02-150405.000000")
if !s.newConceptJobs.StartWith(id, func() (any, error) { return s.writeConcept(in, "") }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "that concept is already being explained"})
return
if startJob(ctx, s.newConceptJobs, id, "that concept is already being explained", func() (any, error) { return s.writeConcept(in, "") }) {
ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)})
}
ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)})
}
func (s *Server) newConceptStatus(ctx *gin.Context) {
@@ -132,8 +130,7 @@ func (s *Server) rewriteConcept(ctx *gin.Context) {
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
var body rewriteBody
@@ -155,11 +152,9 @@ func (s *Server) rewriteConcept(ctx *gin.Context) {
}
in := concept.Input{Topic: topic, Code: code, Previous: prev, Note: body.Note, Existing: conceptRefs(s.Index(), c.Slug)}
slug := c.Slug
if !s.conceptJobs.StartWith(slug, func() (any, error) { return s.writeConcept(in, slug) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "this concept is already being rewritten"})
return
if startJob(ctx, s.conceptJobs, slug, "this concept is already being rewritten", func() (any, error) { return s.writeConcept(in, slug) }) {
ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug))
}
ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug))
}
func (s *Server) rewriteStatus(ctx *gin.Context) {
@@ -186,9 +181,20 @@ type conceptResult struct {
Slug string `json:"slug"`
}
// writeConcept is one job: a new concept when slug is empty, else a rewrite
// of that one. Its error is shown to the admin, so every path returns a
// message meant for them and logs the detail.
// conceptDraft is a written concept waiting to be committed. Slug is set
// for a rewrite; a new concept's is picked when it is saved.
type conceptDraft struct {
Slug string `json:"slug,omitempty"`
Result concept.Result `json:"result"`
Topic string `json:"topic"`
Code string `json:"code,omitempty"`
Model string `json:"model"`
Written time.Time `json:"written"`
}
// writeConcept is one job's work: a new concept when slug is empty, else a
// rewrite of that one. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) writeConcept(in concept.Input, slug string) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
@@ -203,21 +209,34 @@ func (s *Server) writeConcept(in concept.Input, slug string) (any, error) {
log.Printf("[concept] %s: %v", in.Topic, err)
return nil, errors.New("the explanation could not be written")
}
return conceptDraft{Slug: slug, Result: r, Topic: in.Topic, Code: in.Code, Model: s.Claude.Model(), Written: time.Now()}, nil
}
rewrite := slug != ""
if !rewrite {
slug = freeSlug(s.Index(), r.Slug)
// saveConcept commits a concept and answers where it is now.
func (s *Server) saveConcept(raw json.RawMessage) (any, error) {
var d conceptDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
files := concept.Files(r, in, slug, s.Claude.Model(), time.Now())
err = s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error {
slug, rewrite := d.Slug, d.Slug != ""
if !rewrite {
var saved bool
if slug, saved = newConceptSlug(s.Index(), d); saved {
return conceptResult{Slug: slug}, nil
}
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
files := concept.Files(d.Result, concept.Input{Topic: d.Topic, Code: d.Code}, slug, d.Model, d.Written)
err := s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error {
cdir := filepath.Join(dir, index.Concepts, slug)
_, err := os.Stat(cdir)
switch {
case rewrite && os.IsNotExist(err):
return &requestError{http.StatusNotFound, "the concept was deleted while Claude was writing"}
case !rewrite && err == nil:
// Saved since the slug was picked; the next try picks another.
return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; try again", slug)}
// Saved since the slug was picked; saving again picks another.
return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; save again to pick another name", slug)}
}
if err := os.MkdirAll(cdir, 0o755); err != nil {
return err
@@ -235,14 +254,23 @@ func (s *Server) writeConcept(in concept.Input, slug string) (any, error) {
return conceptResult{Slug: slug}, nil
}
// freeSlug is want, or want-2, want-3... if a concept already has it. A
// new question never overwrites a saved concept; rewriting one is its own
// request.
func freeSlug(idx *index.Index, want string) string {
slug := want
// newConceptSlug is the name Claude gave the concept, or name-2, name-3...
// if a concept already has it: a new question never overwrites a saved
// concept, and rewriting one is its own request. saved reports that the
// concept under slug is this very draft (the same question, and the same
// snippet in Claude's own words), which a save run again after a restart that came after its push
// finds, and must not save a second time.
func newConceptSlug(idx *index.Index, d conceptDraft) (slug string, saved bool) {
want, req := d.Result.Slug, strings.TrimSpace(concept.Request(d.Topic, d.Code))
slug = want
for n := 2; ; n++ {
if _, taken := idx.Concepts[slug]; !taken {
return slug
c, taken := idx.Concepts[slug]
if !taken {
return slug, false
}
if strings.TrimSpace(c.Request) == req && c.Snippet != nil &&
strings.TrimSpace(c.Snippet.Content) == strings.TrimSpace(concept.Snippet(d.Result.Snippet, slug)) {
return slug, true
}
slug = fmt.Sprintf("%s-%d", want, n)
}
+7 -7
View File
@@ -13,7 +13,7 @@ import (
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/concept"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/jobs"
)
// fakeConceptClaude explains everything as a Fenwick tree. If gate is set,
@@ -36,19 +36,19 @@ func (f *fakeConceptClaude) JSON(_ context.Context, req claude.Request, out any)
return nil
}
func waitStatus(t *testing.T, r *gin.Engine, path string) explain.Status {
func waitStatus(t *testing.T, r *gin.Engine, path string) jobs.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", path, "", true)
var s explain.Status
var s jobs.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("%s still running", path)
return explain.Status{}
return jobs.Status{}
}
// newConcept starts a concept and returns the slug its job saved it under.
@@ -61,7 +61,7 @@ func newConcept(t *testing.T, r *gin.Engine, body string) string {
var started struct{ ID string }
json.Unmarshal(rec.Body.Bytes(), &started)
s := waitStatus(t, r, "/usaco/api/concept-jobs/"+started.ID)
if s.State != explain.Done {
if s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
res, _ := s.Result.(map[string]any)
@@ -172,7 +172,7 @@ func TestConceptRewrite(t *testing.T) {
t.Fatalf("second rewrite while running = %d, want 409", rec.Code)
}
close(fc.gate)
if s := waitStatus(t, r, path); s.State != explain.Done {
if s := waitStatus(t, r, path); s.State != jobs.Done {
t.Fatalf("rewrite job = %+v", s)
}
for _, want := range []string{"<topic>\nhelp explain fenwick trees", "<previous_version>\n# Fenwick tree", "## Snippet", "<what_to_change>\nstep 2 is wrong"} {
+3 -6
View File
@@ -23,8 +23,7 @@ const evaluateTimeout = 10 * time.Minute
// 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.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
body, p, l, ok := s.readCode(ctx)
@@ -48,11 +47,9 @@ func (s *Server) startEvaluate(ctx *gin.Context) {
Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note,
}
link := p.URL
if !s.evalJobs.StartWith(p.Name, func() (any, error) { return s.evaluate(in, link, l) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "a solution is already being evaluated"})
return
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))
}
ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name))
}
func (s *Server) evaluateStatus(ctx *gin.Context) {
+6 -6
View File
@@ -12,7 +12,7 @@ import (
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/jobs"
)
// fakeEvaluator flags line 1 of whatever it is shown, or fails.
@@ -45,7 +45,7 @@ func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus {
for range 400 {
var s evalStatus
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
@@ -91,7 +91,7 @@ func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) {
t.Fatalf("evaluate = %d %s", rec.Code, rec.Body)
}
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || s.Result == nil {
if s.State != jobs.Done || s.Result == nil {
t.Fatalf("job = %+v", s)
}
ev := s.Result
@@ -124,7 +124,7 @@ func TestEvaluateWithoutARunner(t *testing.T) {
// A runner that fails costs the verdicts, not the evaluation.
fr.err = errors.New("runner down")
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Done || s.Result.Tests != "The tests were not run: the code runner failed." {
if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Done || s.Result.Tests != "The tests were not run: the code runner failed." {
t.Fatalf("with a failing runner = %+v", s)
}
@@ -134,13 +134,13 @@ func TestEvaluateWithoutARunner(t *testing.T) {
}
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || !strings.Contains(fc.user, "the code runner is not configured") {
if s.State != jobs.Done || !strings.Contains(fc.user, "the code runner is not configured") {
t.Fatalf("with no runner = %+v\n%s", s, fc.user)
}
fc.fail = true
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" || s.Result != nil {
if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" || s.Result != nil {
t.Fatalf("a failed evaluation = %+v", s)
}
}
+35 -20
View File
@@ -2,6 +2,7 @@ package handlers
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
@@ -82,8 +83,7 @@ func (s *Server) startExplain(ctx *gin.Context) {
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
var body explainBody
@@ -105,28 +105,33 @@ func (s *Server) startExplain(ctx *gin.Context) {
in.Code = mainFile(p)
}
link := p.URL
if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"})
return
if startJob(ctx, s.explainJobs, p.Name, "an explanation is already being written", func() (any, error) { return s.explain(in, link) }) {
ctx.JSON(http.StatusAccepted, s.explainJobs.Get(p.Name))
}
ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name))
}
func (s *Server) explainStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.jobs.Get(p.Name))
ctx.JSON(http.StatusOK, s.explainJobs.Get(p.Name))
}
}
// explain 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) explain(in explain.Input, link string) error {
// explainDraft is a written explanation waiting to be committed.
type explainDraft struct {
Name string `json:"name"`
Fetched string `json:"fetched,omitempty"`
Markdown string `json:"markdown"`
}
// explain is one job's work. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) explain(in explain.Input, link string) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
fetched, err := s.ensureStatement(ctx, "explain", in.Name, &in.Statement, link)
if err != nil {
return err
return nil, err
}
md, err := explain.Generate(ctx, s.Claude, in, time.Now())
@@ -134,25 +139,35 @@ func (s *Server) explain(in explain.Input, link string) error {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
return nil, errors.New("the explanation could not be written")
}
return explainDraft{Name: in.Name, Fetched: fetched, Markdown: md}, nil
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
// saveExplain commits an explanation. Running it again for a draft already
// pushed changes nothing, so commits nothing.
func (s *Server) saveExplain(raw json.RawMessage) (any, error) {
var d explainDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
err := s.Repo.Mutate(ctx, "Explain "+d.Name, func(dir string) error {
status, err := findOnDisk(dir, d.Name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if err := saveFetched(pdir, fetched); err != nil {
pdir := filepath.Join(dir, status, d.Name)
if err := saveFetched(pdir, d.Fetched); err != nil {
return err
}
return writeOrRemove(filepath.Join(pdir, "explain.md"), md)
return writeOrRemove(filepath.Join(pdir, "explain.md"), d.Markdown)
})
return jobSaveError("explain", name, "the explanation was written but could not be saved to git", err)
return nil, jobSaveError("explain", d.Name, "the explanation was written but could not be saved to git", err)
}
// ensureStatement fetches the statement when none is saved, so a job can
+8 -7
View File
@@ -13,6 +13,7 @@ import (
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/statement"
)
@@ -43,19 +44,19 @@ func (fakeJudge) Fetch(_ context.Context, link string) (string, error) {
return "", statement.ErrUnsupported
}
func waitJob(t *testing.T, r *gin.Engine, name string) explain.Status {
func waitJob(t *testing.T, r *gin.Engine, name string) jobs.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", "/usaco/api/problems/"+name+"/explain", "", true)
var s explain.Status
var s jobs.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return explain.Status{}
return jobs.Status{}
}
func TestExplainNeedsClaudeAndAStatement(t *testing.T) {
@@ -87,7 +88,7 @@ func TestExplainWritesAndCommits(t *testing.T) {
t.Fatalf("second start while running = %d, want 409", rec.Code)
}
close(fc.gate)
if s := waitJob(t, r, "moocast"); s.State != explain.Done {
if s := waitJob(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
@@ -124,13 +125,13 @@ func TestExplainFetchesAMissingStatement(t *testing.T) {
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://cses.fi/x"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Failed || !strings.Contains(s.Error, "paste it") {
if s := waitJob(t, r, "watermelon"); s.State != jobs.Failed || !strings.Contains(s.Error, "paste it") {
t.Fatalf("unfetchable statement: job = %+v, want an error asking to paste it", s)
}
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://usaco.org/moocast"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Done {
if s := waitJob(t, r, "watermelon"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
if b, _ := os.ReadFile(filepath.Join(repo.dir, "solving/watermelon/problem.md")); !strings.Contains(string(b), "walkie-talkies") {
+22 -7
View File
@@ -21,6 +21,7 @@ import (
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
@@ -29,7 +30,9 @@ import (
"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.
@@ -67,13 +70,20 @@ type Server struct {
// 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]
// Separate, so a review, an explanation and an evaluation of one
// problem can run at the same time.
jobs, reviewJobs, evalJobs explain.Jobs
// New concepts are keyed by a job id (the slug is Claude's to pick),
// rewrites by slug.
newConceptJobs, conceptJobs explain.Jobs
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
@@ -96,7 +106,10 @@ func (s *Server) Index() *index.Index { return s.idx.Load() }
// Routes registers everything under api.
func (s *Server) Routes(api *gin.RouterGroup) {
admin := api.Group("", auth.Require(s.Checker))
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)
@@ -127,6 +140,8 @@ func (s *Server) Routes(api *gin.RouterGroup) {
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)
}
+8
View File
@@ -15,6 +15,8 @@ import (
"testing"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/repo"
)
// cookieChecker: the admin is whoever sends the cookie "admin=1".
@@ -31,9 +33,15 @@ type dirRepo struct {
dir string
srv *Server
msg []string
// reject refuses that many edits, as a remote that kept moving would.
reject int
}
func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error {
if d.reject > 0 {
d.reject--
return repo.ErrRejected
}
if err := edit(d.dir); err != nil {
return err
}
+90
View File
@@ -0,0 +1,90 @@
package handlers
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/jobs"
)
// saveTimeout bounds a job's commit: a sync, the edit and a push.
const saveTimeout = 2 * time.Minute
// initJobs registers the job kinds, with the save funcs that commit their
// drafts (explain.go, review.go, concept.go). Routes calls it, and so does
// ResumeJobs, whichever runs first.
func (s *Server) initJobs() {
s.jobsOnce.Do(func() {
if s.Jobs == nil {
s.Jobs = jobs.New("")
}
s.explainJobs = s.Jobs.Kind("explain", jobs.Options{Save: s.saveExplain})
s.reviewJobs = s.Jobs.Kind("review", jobs.Options{Save: s.saveReview, Discard: s.discardReview})
s.evalJobs = s.Jobs.Kind("evaluate", jobs.Options{})
s.newConceptJobs = s.Jobs.Kind("concept", jobs.Options{Save: s.saveConcept})
s.conceptJobs = s.Jobs.Kind("rewrite", jobs.Options{Save: s.saveConcept})
})
}
// ResumeJobs saves the drafts a restart interrupted. main calls it once the
// first sync has made the clone ready.
func (s *Server) ResumeJobs() {
s.initJobs()
s.Jobs.Resume()
}
// startJob starts work as key's job of kind k, or answers why it cannot:
// busy (409) when one is running, 503 while the server shuts down.
func startJob(ctx *gin.Context, k *jobs.Kind, key, busy string, work jobs.Work) bool {
err := k.Start(key, work)
switch {
case err == nil:
return true
case errors.Is(err, jobs.ErrDraining):
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the server is restarting; try again in a minute"})
default:
ctx.JSON(http.StatusConflict, gin.H{"error": busy})
}
return false
}
// claudeReady answers 503 without CLAUDE_API_KEY, and 429 once this month's
// Claude budget is spent; it is checked before any job that calls Claude.
func (s *Server) claudeReady(ctx *gin.Context) bool {
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return false
}
if err := s.Usage.Allow(time.Now()); err != nil {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()})
return false
}
return true
}
// retrySave commits an unsaved job's draft again; the page then polls the
// job's usual status route.
func (s *Server) retrySave(ctx *gin.Context) {
k := s.Jobs.Lookup(ctx.Param("kind"))
if k == nil {
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such job"})
return
}
st, err := k.Retry(ctx.Param("key"))
switch {
case errors.Is(err, jobs.ErrBusy):
ctx.JSON(http.StatusConflict, gin.H{"error": "it is still running"})
case err != nil:
ctx.JSON(http.StatusNotFound, gin.H{"error": "there is nothing unsaved to save"})
default:
ctx.JSON(http.StatusAccepted, st)
}
}
// usage is the Claude spend for the stats page.
func (s *Server) usage(ctx *gin.Context) {
ctx.JSON(http.StatusOK, s.Usage.Summarize(time.Now()))
}
+111
View File
@@ -0,0 +1,111 @@
package handlers
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/concept"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/usage"
)
// A commit the remote keeps refusing leaves the explanation unsaved, not
// lost: saving again commits it without asking Claude a second time.
func TestUnsavedExplanationIsSavedAgain(t *testing.T) {
r, repo, _ := setup(t)
fc := &fakeClaude{}
repo.srv.Claude = fc
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast"}`, true)
repo.reject = 1
do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true)
s := waitJob(t, r, "moocast")
if s.State != jobs.Failed || !s.Unsaved || !strings.Contains(s.Error, "try again") || s.Kind != "explain" || s.Key != "moocast" {
t.Fatalf("rejected save = %+v", s)
}
fc.user = ""
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", false); rec.Code != 401 {
t.Fatalf("public save = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", true); rec.Code != 202 {
t.Fatalf("save again = %d: %s", rec.Code, rec.Body)
}
if s := waitJob(t, r, "moocast"); s.State != jobs.Done || s.Unsaved {
t.Fatalf("saved again = %+v", s)
}
if fc.user != "" {
t.Error("saving again asked Claude again")
}
if b, _ := os.ReadFile(filepath.Join(repo.dir, "solved/moocast/explain.md")); !strings.Contains(string(b), "Think in reverse.") {
t.Errorf("explain.md = %q", b)
}
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", true); rec.Code != 404 {
t.Fatalf("nothing left to save = %d, want 404", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/jobs/nope/moocast/save", "", true); rec.Code != 404 {
t.Fatalf("unknown kind = %d, want 404", rec.Code)
}
}
// A new concept whose save is run again after it was pushed (a restart
// between the push and the record) is found, not saved a second time.
func TestConceptSavedTwiceIsSavedOnce(t *testing.T) {
_, repo, _ := setup(t)
s := repo.srv
raw, _ := json.Marshal(conceptDraft{
Result: concept.Result{Slug: "kmp", Title: "KMP", Snippet: "int kmp();"},
Topic: "kmp", Model: "m", Written: time.Now(),
})
for range 2 {
res, err := s.saveConcept(raw)
if err != nil || res.(conceptResult).Slug != "kmp" {
t.Fatalf("save = %+v, %v", res, err)
}
}
if len(repo.msg) != 1 {
t.Fatalf("commits = %v, want one", repo.msg)
}
}
func TestClaudeBudget(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Claude = &fakeClaude{}
l, err := usage.Open(filepath.Join(t.TempDir(), "usage.jsonl"), 1)
if err != nil {
t.Fatal(err)
}
repo.srv.Usage = l
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast"}`, true)
l.Record(usage.Entry{Kind: "explain", Model: "claude-opus-5-5", Out: 100_000}) // $2
rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true)
if rec.Code != 429 || !strings.Contains(rec.Body.String(), "budget") {
t.Fatalf("over budget = %d: %s", rec.Code, rec.Body)
}
rec = do(r, "GET", "/usaco/api/usage", "", true)
var sum usage.Summary
json.Unmarshal(rec.Body.Bytes(), &sum)
if rec.Code != 200 || !sum.Tracked || sum.Budget != 1 || sum.Month < 2 {
t.Fatalf("usage = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "GET", "/usaco/api/usage", "", false); rec.Code != 401 {
t.Fatalf("public usage = %d, want 401", rec.Code)
}
}
// An admin's cookies on a request from another origin change nothing.
func TestCrossSiteEditRefused(t *testing.T) {
r, repo, _ := setup(t)
rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true, "Sec-Fetch-Site", "same-site")
if rec.Code != 403 || len(repo.msg) != 0 {
t.Fatalf("cross-origin edit = %d, commits %v", rec.Code, repo.msg)
}
if rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true, "Sec-Fetch-Site", "same-origin"); rec.Code != 200 {
t.Fatalf("same-origin edit = %d: %s", rec.Code, rec.Body)
}
}
+55 -21
View File
@@ -3,6 +3,7 @@ package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
@@ -62,8 +63,7 @@ func (s *Server) startReview(ctx *gin.Context) {
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
if s.Transcriber == nil {
@@ -125,11 +125,9 @@ func (s *Server) startReview(ctx *gin.Context) {
id := time.Now().UTC().Format(reviewIDLayout)
rec := recording{name: id + ext, contentType: contentType, data: audio}
link := p.URL
if !s.reviewJobs.Start(p.Name, func() error { return s.review(in, link, id, rec) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "a recording is already being reviewed"})
return
if startJob(ctx, s.reviewJobs, p.Name, "a recording is already being reviewed", func() (any, error) { return s.review(in, link, id, rec) }) {
ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name))
}
ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name))
}
func (s *Server) reviewStatus(ctx *gin.Context) {
@@ -143,16 +141,26 @@ type recording struct {
data []byte
}
// review 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) review(in review.Input, link, id string, rec recording) (err error) {
// reviewDraft is a written review waiting to be committed. Audio is the
// recording's key in the store, kept until the review is saved or replaced.
type reviewDraft struct {
Name string `json:"name"`
ID string `json:"id"`
Fetched string `json:"fetched,omitempty"`
Markdown string `json:"markdown"`
Audio string `json:"audio,omitempty"`
}
// review is one job's work. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) review(in review.Input, link, id string, rec recording) (draft any, err error) {
ctx, cancel := context.WithTimeout(context.Background(), reviewTimeout)
defer cancel()
name := in.Name
fetched, err := s.ensureStatement(ctx, "review", name, &in.Statement, link)
if err != nil {
return err
return nil, err
}
tr, err := s.Transcriber.Transcribe(ctx, rec.name, rec.data)
@@ -160,17 +168,19 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er
var f *transcribe.Failure
if errors.As(err, &f) {
log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[review] %s: transcribing: %v", name, err)
return errors.New("the recording could not be transcribed")
return nil, errors.New("the recording could not be transcribed")
}
in.Transcript, in.Metrics = tr, tr.Metrics()
// The recording is kept only if there is somewhere to keep it, and a
// failure to keep it costs the playback, not the review. It is stored
// before Claude runs so the review can point at it, and removed again
// if the review never gets saved.
// if Claude fails. Once there is a review it stays with the draft: a
// failed commit can be retried, and discardReview removes it if a new
// recording replaces the draft instead.
key := ""
if s.Audio != nil {
k := name + "/" + rec.name
@@ -194,27 +204,51 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[review] %s: %v", name, err)
return errors.New("the review could not be written")
return nil, errors.New("the review could not be written")
}
return reviewDraft{Name: name, ID: id, Fetched: fetched, Markdown: md, Audio: key}, nil
}
err = s.Repo.Mutate(ctx, "Review "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
// saveReview commits a review. The id was chosen when the recording came
// in, so running it again for a draft already pushed rewrites the same
// file and commits nothing.
func (s *Server) saveReview(raw json.RawMessage) (any, error) {
var d reviewDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
err := s.Repo.Mutate(ctx, "Review "+d.Name, func(dir string) error {
status, err := findOnDisk(dir, d.Name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if err := saveFetched(pdir, fetched); err != nil {
pdir := filepath.Join(dir, status, d.Name)
if err := saveFetched(pdir, d.Fetched); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(pdir, "reviews"), 0o755); err != nil {
return err
}
return writeOrRemove(filepath.Join(pdir, "reviews", id+".md"), md)
return writeOrRemove(filepath.Join(pdir, "reviews", d.ID+".md"), d.Markdown)
})
return jobSaveError("review", name, "the review was written but could not be saved to git", err)
return nil, jobSaveError("review", d.Name, "the review was written but could not be saved to git", err)
}
// discardReview removes the recording of a review that was never saved and
// has been replaced by a new one.
func (s *Server) discardReview(raw json.RawMessage) {
var d reviewDraft
if json.Unmarshal(raw, &d) != nil || d.Audio == "" || s.Audio == nil {
return
}
if err := s.Audio.Delete(context.Background(), d.Audio); err != nil {
log.Printf("[review] %s: removing the unsaved review's recording: %v", d.Name, err)
}
}
// findReview is the problem's review with the URL's id.
+9 -9
View File
@@ -18,8 +18,8 @@ import (
"adam-french.co.uk/usaco-site/internal/audiostore"
"adam-french.co.uk/usaco-site/internal/claude"
"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/review"
"adam-french.co.uk/usaco-site/internal/transcribe"
)
@@ -121,18 +121,18 @@ func upload(r *gin.Engine, name, filename string, size int, fields ...string) *h
return do(r, "POST", "/usaco/api/problems/"+name+"/review", body.String(), true, "Content-Type", w.FormDataContentType())
}
func waitReview(t *testing.T, r *gin.Engine, name string) explain.Status {
func waitReview(t *testing.T, r *gin.Engine, name string) jobs.Status {
t.Helper()
for range 400 {
var s explain.Status
var s jobs.Status
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/review", "", true).Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("review still running")
return explain.Status{}
return jobs.Status{}
}
func withStatement(t *testing.T, r *gin.Engine) {
@@ -183,7 +183,7 @@ func TestReviewWritesAndCommits(t *testing.T) {
if rec := upload(r, "moocast", "Take 1.M4A", 10, "note", "mock interview", "includeCode", "true"); rec.Code != 202 {
t.Fatalf("start = %d: %s", rec.Code, rec.Body)
}
if s := waitReview(t, r, "moocast"); s.State != explain.Done {
if s := waitReview(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
if !strings.HasSuffix(ft.file, ".m4a") || string(ft.audio[:3]) != "ID3" {
@@ -241,7 +241,7 @@ func TestReviewKeepsAndRemovesTheRecording(t *testing.T) {
withStatement(t, r)
upload(r, "moocast", "take.mp3", 100)
if s := waitReview(t, r, "moocast"); s.State != explain.Done {
if s := waitReview(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
var p index.Problem
@@ -288,7 +288,7 @@ func TestReviewFailures(t *testing.T) {
commits := len(repo.msg)
upload(r, "moocast", "a.mp3", 10)
if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "no speech was found in the recording" {
if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "no speech was found in the recording" {
t.Fatalf("transcription failure: job = %+v", s)
}
@@ -296,7 +296,7 @@ func TestReviewFailures(t *testing.T) {
// behind when the review fails.
ft.err, fr.fail = nil, true
upload(r, "moocast", "a.mp3", 10)
if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" {
if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" {
t.Fatalf("Claude failure: job = %+v", s)
}
if len(repo.msg) != commits || len(store.keys()) != 0 {