- 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]>
190 lines
6.8 KiB
Go
190 lines
6.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"adam-french.co.uk/usaco-site/internal/claude"
|
|
"adam-french.co.uk/usaco-site/internal/concept"
|
|
"adam-french.co.uk/usaco-site/internal/jobs"
|
|
)
|
|
|
|
// fakeConceptClaude explains everything as a Fenwick tree. If gate is set,
|
|
// it waits for it to close first, so a test can catch a job mid-run.
|
|
type fakeConceptClaude struct {
|
|
gate chan struct{}
|
|
user string
|
|
}
|
|
|
|
func (f *fakeConceptClaude) Model() string { return "fake-model" }
|
|
func (f *fakeConceptClaude) JSON(_ context.Context, req claude.Request, out any) error {
|
|
if f.gate != nil {
|
|
<-f.gate
|
|
}
|
|
f.user = req.User
|
|
*out.(*concept.Result) = concept.Result{
|
|
Slug: "fenwick-tree", Title: "Fenwick tree", Summary: "Prefix sums with updates.",
|
|
Tags: []string{"range-query"}, Intuition: "Lowbits.", Snippet: "struct BIT {};",
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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 jobs.Status
|
|
json.Unmarshal(rec.Body.Bytes(), &s)
|
|
if s.State != jobs.Running {
|
|
return s
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
t.Fatalf("%s still running", path)
|
|
return jobs.Status{}
|
|
}
|
|
|
|
// newConcept starts a concept and returns the slug its job saved it under.
|
|
func newConcept(t *testing.T, r *gin.Engine, body string) string {
|
|
t.Helper()
|
|
rec := do(r, "POST", "/usaco/api/concepts", body, true)
|
|
if rec.Code != 202 {
|
|
t.Fatalf("start = %d: %s", rec.Code, rec.Body)
|
|
}
|
|
var started struct{ ID string }
|
|
json.Unmarshal(rec.Body.Bytes(), &started)
|
|
s := waitStatus(t, r, "/usaco/api/concept-jobs/"+started.ID)
|
|
if s.State != jobs.Done {
|
|
t.Fatalf("job = %+v, want done", s)
|
|
}
|
|
res, _ := s.Result.(map[string]any)
|
|
slug, _ := res["slug"].(string)
|
|
return slug
|
|
}
|
|
|
|
func TestConceptGuards(t *testing.T) {
|
|
r, repo, _ := setup(t)
|
|
if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, true); rec.Code != 503 {
|
|
t.Fatalf("without Claude = %d, want 503", rec.Code)
|
|
}
|
|
repo.srv.Claude = &fakeConceptClaude{}
|
|
if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, false); rec.Code != 401 {
|
|
t.Fatalf("public start = %d, want 401", rec.Code)
|
|
}
|
|
if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":" "}`, true); rec.Code != 400 {
|
|
t.Fatalf("empty topic = %d, want 400", rec.Code)
|
|
}
|
|
if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"`+strings.Repeat("a", maxNote+1)+`"}`, true); rec.Code != 400 {
|
|
t.Fatalf("long topic = %d, want 400", rec.Code)
|
|
}
|
|
for _, path := range []string{"/usaco/api/concepts/nope", "/usaco/api/concepts/..", "/usaco/api/concepts/A"} {
|
|
if rec := do(r, "GET", path, "", false); rec.Code != 404 {
|
|
t.Errorf("GET %s = %d, want 404", path, rec.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestConceptWritesAndCommits(t *testing.T) {
|
|
r, repo, _ := setup(t)
|
|
fc := &fakeConceptClaude{}
|
|
repo.srv.Claude = fc
|
|
|
|
code := "bool canSort(vector<int>& nums, int k) {\n return true;\n}"
|
|
body, _ := json.Marshal(conceptBody{Topic: "help explain fenwick trees", Code: code})
|
|
if slug := newConcept(t, r, string(body)); slug != "fenwick-tree" {
|
|
t.Fatalf("slug = %q", slug)
|
|
}
|
|
if !strings.Contains(fc.user, "<topic>\nhelp explain fenwick trees\n</topic>") || !strings.Contains(fc.user, "canSort") {
|
|
t.Errorf("prompt is missing the topic or code:\n%s", fc.user)
|
|
}
|
|
cdir := filepath.Join(repo.dir, "concepts", "fenwick-tree")
|
|
snip, _ := os.ReadFile(filepath.Join(cdir, "snippet.cpp"))
|
|
if string(snip) != "// concept: fenwick-tree\nstruct BIT {};\n" {
|
|
t.Errorf("snippet.cpp = %q", snip)
|
|
}
|
|
req, _ := os.ReadFile(filepath.Join(cdir, "request.md"))
|
|
if topic, got := concept.ParseRequest(string(req)); topic != "help explain fenwick trees" || got != code {
|
|
t.Errorf("request.md = %q", req)
|
|
}
|
|
if got := repo.msg[len(repo.msg)-1]; got != "Explain concept fenwick-tree" {
|
|
t.Errorf("commit = %q", got)
|
|
}
|
|
|
|
// The public sees the library and the page.
|
|
rec := do(r, "GET", "/usaco/api/concepts", "", false)
|
|
var list struct {
|
|
Concepts []map[string]any `json:"concepts"`
|
|
}
|
|
json.Unmarshal(rec.Body.Bytes(), &list)
|
|
if len(list.Concepts) != 1 || list.Concepts[0]["title"] != "Fenwick tree" || list.Concepts[0]["content"] != nil {
|
|
t.Fatalf("list = %s", rec.Body)
|
|
}
|
|
rec = do(r, "GET", "/usaco/api/concepts/fenwick-tree", "", false)
|
|
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "## Intuition") || !strings.Contains(rec.Body.String(), "struct BIT") {
|
|
t.Fatalf("page = %d: %s", rec.Code, rec.Body)
|
|
}
|
|
|
|
// The same answer to a new question never overwrites the saved one.
|
|
if slug := newConcept(t, r, `{"topic":"fenwick again"}`); slug != "fenwick-tree-2" {
|
|
t.Fatalf("second slug = %q, want fenwick-tree-2", slug)
|
|
}
|
|
if !strings.Contains(fc.user, "- fenwick-tree: Fenwick tree") {
|
|
t.Errorf("prompt does not list the saved concept:\n%s", fc.user)
|
|
}
|
|
if req, _ := os.ReadFile(filepath.Join(cdir, "request.md")); !strings.Contains(string(req), "canSort") {
|
|
t.Error("the first concept was overwritten")
|
|
}
|
|
|
|
// Public visitors cannot delete; the admin can.
|
|
if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", false); rec.Code != 401 {
|
|
t.Fatalf("public delete = %d, want 401", rec.Code)
|
|
}
|
|
if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", true); rec.Code != 200 {
|
|
t.Fatalf("delete = %d: %s", rec.Code, rec.Body)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) {
|
|
t.Error("the concept's directory is still there")
|
|
}
|
|
if got := repo.msg[len(repo.msg)-1]; got != "Forget concept fenwick-tree-2" {
|
|
t.Errorf("commit = %q", got)
|
|
}
|
|
}
|
|
|
|
func TestConceptRewrite(t *testing.T) {
|
|
r, repo, _ := setup(t)
|
|
repo.srv.Claude = &fakeConceptClaude{}
|
|
newConcept(t, r, `{"topic":"help explain fenwick trees"}`)
|
|
|
|
fc := &fakeConceptClaude{gate: make(chan struct{})}
|
|
repo.srv.Claude = fc
|
|
path := "/usaco/api/concepts/fenwick-tree/explain"
|
|
if rec := do(r, "POST", path, `{"note":"step 2 is wrong"}`, true); rec.Code != 202 {
|
|
t.Fatalf("rewrite = %d: %s", rec.Code, rec.Body)
|
|
}
|
|
if rec := do(r, "POST", path, `{}`, true); rec.Code != 409 {
|
|
t.Fatalf("second rewrite while running = %d, want 409", rec.Code)
|
|
}
|
|
close(fc.gate)
|
|
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"} {
|
|
if !strings.Contains(fc.user, want) {
|
|
t.Errorf("rewrite prompt is missing %q:\n%s", want, fc.user)
|
|
}
|
|
}
|
|
if strings.Contains(fc.user, "<saved_concepts>") {
|
|
t.Error("a rewrite should not list the concept as taken")
|
|
}
|
|
if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) {
|
|
t.Error("a rewrite saved a new concept instead of replacing its own")
|
|
}
|
|
}
|