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
+376
View File
@@ -0,0 +1,376 @@
// Package jobs runs the site's slow work in the background: Claude writing
// an explanation, a concept or a review, or judging a draft. Each takes a
// minute or more, longer than nginx waits for a response, so the request
// only starts a job and the page polls its Status.
//
// Every job belongs to a Kind ("explain", "review"...) and has a key within
// it (a problem name, a concept slug, a job id); a kind runs at most one job
// per key at a time.
//
// A job that commits is split in two. Its work (the expensive part: Claude)
// returns a draft, which is written to disk before the kind's save func
// commits it. So a commit that fails (the remote kept moving, Gitea was
// down) or a restart in the middle of one does not throw away a paid-for
// answer: the job is left unsaved, Retry runs the save again, and Resume
// does so on its own after a restart.
//
// Records live in Dir/<kind>/<key>.json, so a finished job's status and
// result survive a restart too. With no Dir everything is in memory, which
// the tests use.
package jobs
import (
"encoding/json"
"errors"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
// A job's states. Idle means the key has never had a job.
const (
Idle = "idle"
Running = "running"
Done = "done"
Failed = "error"
)
var (
// ErrBusy is a Start or Retry for a key whose job is still running.
ErrBusy = errors.New("a job is already running")
// ErrDraining is a Start during shutdown: the running jobs are being
// let finish, and nothing new begins.
ErrDraining = errors.New("the server is restarting")
// ErrNothingToSave is a Retry for a key with no unsaved draft.
ErrNothingToSave = errors.New("nothing to save")
)
// interrupted is the error a job is left with when the server stopped
// before its work finished. Only work that had not produced a draft yet
// ends up here; a draft is saved again by Resume.
const interrupted = "the server restarted while this was running; start it again"
// finishedTTL is how long a finished record without a draft is kept on
// disk. New concepts are keyed by a fresh id each, so their records would
// otherwise pile up.
const finishedTTL = 7 * 24 * time.Hour
// Status is what the page polls for.
type Status struct {
Kind string `json:"kind"`
Key string `json:"key"`
State string `json:"state"`
Error string `json:"error,omitempty"`
Started *time.Time `json:"started,omitempty"`
Finished *time.Time `json:"finished,omitempty"`
// Result is a finished job's answer, for kinds that return one.
Result any `json:"result,omitempty"`
// Unsaved means the work finished but its commit did not: the draft is
// kept, and POST /jobs/<kind>/<key>/save tries the commit again.
Unsaved bool `json:"unsaved,omitempty"`
}
// record is a Status as stored, with the draft the page never sees.
type record struct {
Status
Draft json.RawMessage `json:"draft,omitempty"`
}
// Work is a job's expensive part. For a kind with a save func it returns
// the draft to save, which must marshal to JSON; otherwise its result.
// Its error is shown to the admin, so it must be a message meant for them.
type Work func() (any, error)
// Save commits a draft and returns the job's result. It may run more than
// once for one draft (a retry, or a resume after a restart that came after
// the commit was pushed), so it must cope with finding its work already
// done. Its error is shown to the admin.
type Save func(draft json.RawMessage) (any, error)
// Registry holds every kind, and knows when the server is shutting down.
type Registry struct {
dir string
wg sync.WaitGroup
draining atomic.Bool
mu sync.Mutex
kinds []*Kind
}
// New is a registry keeping records under dir; "" keeps them in memory.
func New(dir string) *Registry { return &Registry{dir: dir} }
// Kind is one sort of job.
type Kind struct {
r *Registry
name string
dir string
save Save
discard func(draft json.RawMessage)
mu sync.Mutex
m map[string]*record
}
// Options configure a kind.
type Options struct {
// Save commits a draft; nil for a kind whose work's answer is the
// result (an evaluation), which commits nothing.
Save Save
// Discard cleans up after a draft that will never be saved, because a
// new job for the key replaced it (a review's stored recording).
Discard func(draft json.RawMessage)
}
// Kind registers a kind and loads its records. A record left running by
// the last process is settled here: one with a draft waits for Resume,
// one without is marked interrupted.
func (r *Registry) Kind(name string, o Options) *Kind {
k := &Kind{r: r, name: name, save: o.Save, discard: o.Discard, m: map[string]*record{}}
if r.dir != "" {
k.dir = filepath.Join(r.dir, name)
if err := os.MkdirAll(k.dir, 0o755); err != nil {
log.Printf("[jobs] %s: %v; its jobs are kept in memory only", name, err)
k.dir = ""
}
}
k.load()
r.mu.Lock()
r.kinds = append(r.kinds, k)
r.mu.Unlock()
return k
}
func (k *Kind) load() {
if k.dir == "" {
return
}
entries, err := os.ReadDir(k.dir)
if err != nil {
log.Printf("[jobs] %s: %v", k.name, err)
return
}
for _, e := range entries {
path := filepath.Join(k.dir, e.Name())
if !strings.HasSuffix(e.Name(), ".json") {
continue
}
b, err := os.ReadFile(path)
if err != nil {
log.Printf("[jobs] %s: %v", path, err)
continue
}
var rec record
if err := json.Unmarshal(b, &rec); err != nil || rec.Key == "" {
log.Printf("[jobs] %s: unreadable, removed: %v", path, err)
os.Remove(path)
continue
}
if rec.State != Running && len(rec.Draft) == 0 && rec.Finished != nil && time.Since(*rec.Finished) > finishedTTL {
os.Remove(path)
continue
}
if rec.State == Running && len(rec.Draft) == 0 {
now := time.Now()
rec.State, rec.Error, rec.Finished = Failed, interrupted, &now
k.store(&rec)
}
// A loaded result is generic JSON (maps and slices), which goes back
// out to the page as it was stored.
k.m[rec.Key] = &rec
}
}
// Start runs work in the background unless key's job is running, or the
// server is shutting down.
func (k *Kind) Start(key string, work Work) error {
if k.r.draining.Load() {
return ErrDraining
}
k.mu.Lock()
defer k.mu.Unlock()
old := k.m[key]
if old != nil && old.State == Running {
return ErrBusy
}
if old != nil && len(old.Draft) > 0 && k.discard != nil {
go k.discard(old.Draft)
}
now := time.Now()
rec := &record{Status: Status{Kind: k.name, Key: key, State: Running, Started: &now}}
k.m[key] = rec
k.store(rec)
k.r.wg.Add(1)
go func() {
defer k.r.wg.Done()
out, err := work()
if err != nil {
k.finish(key, nil, err, false)
return
}
if k.save == nil {
k.finish(key, out, nil, false)
return
}
draft, err := json.Marshal(out)
if err != nil {
log.Printf("[jobs] %s %s: the draft does not marshal: %v", k.name, key, err)
k.finish(key, nil, errors.New("the answer could not be kept"), false)
return
}
k.mu.Lock()
rec.Draft = draft
k.store(rec)
k.mu.Unlock()
k.runSave(key, draft)
}()
return nil
}
// runSave commits key's draft; the caller has counted it in the wait group
// when it runs in the background.
func (k *Kind) runSave(key string, draft json.RawMessage) {
res, err := k.save(draft)
k.finish(key, res, err, err != nil)
}
func (k *Kind) finish(key string, res any, err error, unsaved bool) {
k.mu.Lock()
defer k.mu.Unlock()
rec := k.m[key]
if rec == nil {
return
}
end := time.Now()
rec.Finished = &end
rec.State, rec.Error, rec.Result, rec.Unsaved = Done, "", res, false
if err != nil {
rec.State, rec.Error, rec.Result, rec.Unsaved = Failed, err.Error(), nil, unsaved
}
if !unsaved {
// Saved, or never got as far as a draft: nothing left to retry.
rec.Draft = nil
}
k.store(rec)
}
// Retry runs an unsaved job's save again.
func (k *Kind) Retry(key string) (Status, error) {
if k.save == nil {
return Status{}, ErrNothingToSave
}
k.mu.Lock()
rec := k.m[key]
switch {
case rec != nil && rec.State == Running:
k.mu.Unlock()
return Status{}, ErrBusy
case rec == nil || len(rec.Draft) == 0:
k.mu.Unlock()
return Status{}, ErrNothingToSave
}
rec.State, rec.Error, rec.Unsaved, rec.Finished = Running, "", false, nil
k.store(rec)
draft, st := rec.Draft, rec.Status
k.mu.Unlock()
k.r.wg.Add(1)
go func() {
defer k.r.wg.Done()
k.runSave(key, draft)
}()
return st, nil
}
// Get is key's latest job.
func (k *Kind) Get(key string) Status {
k.mu.Lock()
defer k.mu.Unlock()
if rec := k.m[key]; rec != nil {
return rec.Status
}
return Status{Kind: k.name, Key: key, State: Idle}
}
// store writes rec to disk, through a temporary file so a crash never
// leaves half a record. The caller holds k.mu.
func (k *Kind) store(rec *record) {
if k.dir == "" {
return
}
b, err := json.Marshal(rec)
if err != nil {
log.Printf("[jobs] %s %s: %v", k.name, rec.Key, err)
return
}
path := filepath.Join(k.dir, url.PathEscape(rec.Key)+".json")
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
log.Printf("[jobs] %s: %v", path, err)
return
}
if err := os.Rename(tmp, path); err != nil {
log.Printf("[jobs] %s: %v", path, err)
}
}
// Lookup is the kind called name, or nil.
func (r *Registry) Lookup(name string) *Kind {
r.mu.Lock()
defer r.mu.Unlock()
for _, k := range r.kinds {
if k.name == name {
return k
}
}
return nil
}
// Resume saves the drafts the last process left running: it stopped after
// the work and before (or during) the commit. Call it once the clone is
// ready, since saving needs it.
func (r *Registry) Resume() {
r.mu.Lock()
kinds := append([]*Kind(nil), r.kinds...)
r.mu.Unlock()
for _, k := range kinds {
k.mu.Lock()
var keys []string
var drafts []json.RawMessage
for key, rec := range k.m {
if rec.State == Running && len(rec.Draft) > 0 && k.save != nil {
keys, drafts = append(keys, key), append(drafts, rec.Draft)
}
}
k.mu.Unlock()
for i, key := range keys {
log.Printf("[jobs] %s %s: saving the draft a restart interrupted", k.name, key)
r.wg.Add(1)
go func(key string, draft json.RawMessage) {
defer r.wg.Done()
k.runSave(key, draft)
}(key, drafts[i])
}
}
}
// Drain stops new jobs from starting and waits for the running ones, or
// until stop is closed. It reports whether they all finished.
func (r *Registry) Drain(stop <-chan struct{}) bool {
r.draining.Store(true)
done := make(chan struct{})
go func() {
r.wg.Wait()
close(done)
}()
select {
case <-done:
return true
case <-stop:
return false
}
}