Files
usaco/site/internal/handlers/jobs_test.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

112 lines
3.9 KiB
Go

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)
}
}