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
+66 -4
View File
@@ -14,10 +14,16 @@ package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin"
@@ -26,9 +32,11 @@ import (
"adam-french.co.uk/usaco-site/internal/auth"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/handlers"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/runner"
"adam-french.co.uk/usaco-site/internal/transcribe"
"adam-french.co.uk/usaco-site/internal/usage"
)
func main() {
@@ -67,6 +75,7 @@ func main() {
log.Fatal("GIT_REMOTE_URL is not set")
}
var err error
srv := &handlers.Server{Checker: checker, WebhookSecret: os.Getenv("WEBHOOK_SECRET")}
if srv.WebhookSecret == "" {
log.Println("[webhook] WEBHOOK_SECRET is not set: the push hook is off, pulls happen on the interval only")
@@ -75,13 +84,33 @@ func main() {
// CLAUDE
// Optional: without a key the site runs as before and the Explain
// button answers 503.
// Every call's cost goes in a ledger beside the clone, and
// CLAUDE_MONTHLY_BUDGET (dollars) stops new jobs once a month has spent
// it.
budget := 0.0
if v := os.Getenv("CLAUDE_MONTHLY_BUDGET"); v != "" {
if budget, err = strconv.ParseFloat(v, 64); err != nil || budget < 0 {
log.Fatalf("CLAUDE_MONTHLY_BUDGET=%q is not a dollar amount", v)
}
}
ledger, err := usage.Open(filepath.Join(dataDir, "usage.jsonl"), budget)
if err != nil {
log.Fatal(err)
}
srv.Usage = ledger
if c, err := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL")); err == nil {
c.Ledger = ledger
srv.Claude = c
log.Printf("[claude] explanations use %s", c.Model())
log.Printf("[claude] explanations use %s; monthly budget %s", c.Model(), dollars(budget))
} else {
log.Printf("[claude] %v: explanations are off", err)
}
// JOBS
// Their records (and the drafts of answers not yet committed) are kept
// beside the clone, so a restart loses neither.
srv.Jobs = jobs.New(filepath.Join(dataDir, "jobs"))
// REVIEWS
// A recording needs a transcriber as well as Claude. OPENAI_API_KEY is
// accepted too, as the key most people already have under that name.
@@ -164,10 +193,41 @@ func main() {
r.NoRoute(handlers.SPA(staticDir, basePath))
addr := ":" + getenv("PORT", "8080")
log.Printf("listening on %s%s/", addr, basePath)
if err := r.Run(addr); err != nil {
log.Fatal(err)
hs := &http.Server{Addr: addr, Handler: r}
go func() {
log.Printf("listening on %s%s/", addr, basePath)
if err := hs.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
// SHUTDOWN
// A deploy stops the container with SIGTERM. Without a handler the
// process (PID 1, which has no default one) ignored it until Docker's
// SIGKILL, mid-job. Now the running jobs get SHUTDOWN_GRACE to finish,
// while the server keeps answering the pages that poll them and turns
// new jobs away; the compose file's stop_grace_period must be longer.
// A job cut off anyway is settled by the next start (internal/jobs).
stop, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer cancel()
<-stop.Done()
grace := duration("SHUTDOWN_GRACE", 5*time.Minute)
log.Printf("[shutdown] waiting up to %s for running jobs", grace)
drain, undrain := context.WithTimeout(context.Background(), grace)
defer undrain()
if !srv.Jobs.Drain(drain.Done()) {
log.Println("[shutdown] jobs still running; they are settled on the next start")
}
ctx, done := context.WithTimeout(context.Background(), 10*time.Second)
defer done()
hs.Shutdown(ctx)
}
func dollars(budget float64) string {
if budget == 0 {
return "none"
}
return fmt.Sprintf("$%.2f", budget)
}
func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, interval time.Duration) {
@@ -183,6 +243,8 @@ func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, inte
for !pull() {
time.Sleep(30 * time.Second)
}
// Commits a restart interrupted need the clone, so they wait for it.
srv.ResumeJobs()
tick := time.NewTicker(interval)
defer tick.Stop()
for {