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
+181
View File
@@ -0,0 +1,181 @@
package jobs
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
)
func wait(t *testing.T, k *Kind, key string) Status {
t.Helper()
for range 400 {
if s := k.Get(key); s.State != Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return Status{}
}
func TestResultKind(t *testing.T) {
k := New("").Kind("evaluate", Options{})
if s := k.Get("a"); s.State != Idle || s.Kind != "evaluate" || s.Key != "a" {
t.Fatalf("fresh = %+v", s)
}
release := make(chan struct{})
if err := k.Start("a", func() (any, error) { <-release; return "verdict", nil }); err != nil {
t.Fatal(err)
}
if err := k.Start("a", func() (any, error) { return nil, nil }); !errors.Is(err, ErrBusy) {
t.Fatalf("second start = %v, want ErrBusy", err)
}
if err := k.Start("b", func() (any, error) { return nil, nil }); err != nil {
t.Fatalf("another key's job = %v", err)
}
close(release)
if s := wait(t, k, "a"); s.State != Done || s.Result != "verdict" {
t.Fatalf("done = %+v", s)
}
k.Start("a", func() (any, error) { return nil, errors.New("Claude declined") })
if s := wait(t, k, "a"); s.State != Failed || s.Error != "Claude declined" || s.Unsaved {
t.Fatalf("failed = %+v", s)
}
}
// A commit that fails keeps the draft; Retry saves it.
func TestRetrySavesTheDraft(t *testing.T) {
var mu sync.Mutex
var saved []string
fail := true
k := New(t.TempDir()).Kind("explain", Options{Save: func(d json.RawMessage) (any, error) {
mu.Lock()
defer mu.Unlock()
if fail {
return nil, errors.New("the repository changed while saving; try again")
}
var s string
json.Unmarshal(d, &s)
saved = append(saved, s)
return nil, nil
}})
if _, err := k.Retry("p"); !errors.Is(err, ErrNothingToSave) {
t.Fatalf("retry with no job = %v", err)
}
k.Start("p", func() (any, error) { return "# explanation", nil })
s := wait(t, k, "p")
if s.State != Failed || !s.Unsaved {
t.Fatalf("failed save = %+v", s)
}
mu.Lock()
fail = false
mu.Unlock()
if _, err := k.Retry("p"); err != nil {
t.Fatal(err)
}
if s := wait(t, k, "p"); s.State != Done || s.Unsaved {
t.Fatalf("retried = %+v", s)
}
if len(saved) != 1 || saved[0] != "# explanation" {
t.Fatalf("saved %q", saved)
}
if _, err := k.Retry("p"); !errors.Is(err, ErrNothingToSave) {
t.Fatalf("retry after saving = %v", err)
}
}
// A restart settles what the last process left running: a job still at
// its work is interrupted, one with a draft is saved by Resume, and a
// finished one keeps its result.
func TestRestart(t *testing.T) {
dir := t.TempDir()
write := func(kind, key string, rec record) {
os.MkdirAll(filepath.Join(dir, kind), 0o755)
b, _ := json.Marshal(rec)
os.WriteFile(filepath.Join(dir, kind, key+".json"), b, 0o600)
}
now := time.Now()
old := now.Add(-30 * 24 * time.Hour)
write("explain", "working", record{Status: Status{Kind: "explain", Key: "working", State: Running, Started: &now}})
write("explain", "saving", record{Status: Status{Kind: "explain", Key: "saving", State: Running, Started: &now}, Draft: json.RawMessage(`"md"`)})
write("explain", "stale", record{Status: Status{Kind: "explain", Key: "stale", State: Done, Finished: &old}})
write("evaluate", "done", record{Status: Status{Kind: "evaluate", Key: "done", State: Done, Finished: &now, Result: map[string]any{"verdict": "correct"}}})
r := New(dir)
var saved []string
var mu sync.Mutex
ex := r.Kind("explain", Options{Save: func(d json.RawMessage) (any, error) {
mu.Lock()
saved = append(saved, string(d))
mu.Unlock()
return nil, nil
}})
ev := r.Kind("evaluate", Options{})
if s := ex.Get("working"); s.State != Failed || s.Error != interrupted {
t.Fatalf("interrupted = %+v", s)
}
if s := ex.Get("stale"); s.State != Idle {
t.Fatalf("stale record kept: %+v", s)
}
if _, err := os.Stat(filepath.Join(dir, "explain", "stale.json")); !os.IsNotExist(err) {
t.Fatal("stale record not removed")
}
if s := ev.Get("done"); s.State != Done || s.Result.(map[string]any)["verdict"] != "correct" {
t.Fatalf("finished = %+v", s)
}
if s := ex.Get("saving"); s.State != Running {
t.Fatalf("before Resume = %+v", s)
}
r.Resume()
if s := wait(t, ex, "saving"); s.State != Done {
t.Fatalf("resumed = %+v", s)
}
if len(saved) != 1 || saved[0] != `"md"` {
t.Fatalf("saved %q", saved)
}
}
func TestDrain(t *testing.T) {
r := New("")
k := r.Kind("explain", Options{})
release := make(chan struct{})
k.Start("a", func() (any, error) { <-release; return nil, nil })
stop := make(chan struct{})
close(stop)
if r.Drain(stop) {
t.Fatal("Drain reported done with a job running")
}
if err := k.Start("b", func() (any, error) { return nil, nil }); !errors.Is(err, ErrDraining) {
t.Fatalf("start while draining = %v", err)
}
close(release)
if !r.Drain(make(chan struct{})) {
t.Fatal("Drain did not finish")
}
}
// Replacing an unsaved draft with a new job hands the old one to Discard.
func TestDiscard(t *testing.T) {
discarded := make(chan string, 1)
k := New("").Kind("review", Options{
Save: func(json.RawMessage) (any, error) { return nil, errors.New("push failed") },
Discard: func(d json.RawMessage) { discarded <- string(d) },
})
k.Start("p", func() (any, error) { return "first", nil })
wait(t, k, "p")
k.Start("p", func() (any, error) { return nil, errors.New("no") })
select {
case d := <-discarded:
if d != `"first"` {
t.Fatalf("discarded %s", d)
}
case <-time.After(time.Second):
t.Fatal("old draft not discarded")
}
}