diff --git a/site/.env.example b/site/.env.example index 81305dd..2337002 100644 --- a/site/.env.example +++ b/site/.env.example @@ -5,12 +5,16 @@ # --- Core ------------------------------------------------------------------- # URL prefix everything is served under. The SPA is built for /usaco. BASE_PATH= -# The clone lives in $DATA_DIR/repo (default /data). +# The clone lives in $DATA_DIR/repo (default /data), beside the job records +# ($DATA_DIR/jobs) and the Claude spend ledger ($DATA_DIR/usage.jsonl). DATA_DIR= # Listen port (default 8080). PORT= # "true" enables gin debug logging, and is required for AUTH_MODE=dev. DEV_MODE= +# How long a SIGTERM waits for running jobs before the server exits, a Go +# duration. Default 5m; the container's stop_grace_period must be longer. +SHUTDOWN_GRACE= # --- Git -------------------------------------------------------------------- # What to clone. Production: http://gitea:3000/adamf/usaco.git (Gitea on the @@ -47,6 +51,10 @@ AUTH_VALIDATE_URL= CLAUDE_API_KEY= # Model for explanations (default claude-opus-5-5). CLAUDE_MODEL= +# Monthly cap on the estimated Claude spend, in dollars (e.g. 20). Once a +# calendar month (UTC) reaches it, new Claude jobs are refused until the 1st. +# Blank: no cap; spend is still recorded and shown on the stats page. +CLAUDE_MONTHLY_BUDGET= # --- Recording reviews ------------------------------------------------------ # A review needs CLAUDE_API_KEY and a transcriber: anything that speaks diff --git a/site/CLAUDE.md b/site/CLAUDE.md index d2b4c60..6ca6f06 100644 --- a/site/CLAUDE.md +++ b/site/CLAUDE.md @@ -14,13 +14,16 @@ cd web && npm run dev # SPA hot reload; proxies /usaco/api to localhost:8080 One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, all under `/usaco`. It is deployed as one container inside the `web_server` stack, behind its nginx. It has the same shape as `../job-tracker`, from which `internal/auth` and `handlers.SPA` were copied. -- **Git is the only store.** `internal/repo` owns the clone and serializes every git command. A sync is fetch + hard reset (the remote wins). `Mutate` does sync, edit, commit and push, and replays the edit once if the push is rejected. Its `onChange` callback (`Server.Reload`) rebuilds the index under the same lock. +- **Git is the only store** for content. `internal/repo` owns the clone and serializes every git command. A sync is fetch + hard reset (the remote wins). `Mutate` does sync, edit, commit and push, and replays the edit once if the push is rejected. Its `onChange` callback (`Server.Reload`) rebuilds the index under the same lock, when HEAD moved. Beside the clone, `DATA_DIR` holds only operational state: job records (`jobs/`) and the Claude spend ledger (`usage.jsonl`). - **The index is an immutable snapshot**, swapped in through an `atomic.Pointer`. Handlers read `s.Index()` once per request. - **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call. `problem.md` (the judge's statement) is admin-only even on solved problems. -- **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network. -- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`. +- **Explanations run in the background.** `POST /explain` starts a job (`internal/jobs`, kind "explain", keyed by problem) and returns 202. The job's work calls Claude (`internal/claude`, streamed, JSON schema) and returns a draft; the kind's save func (`saveExplain`) commits `explain.md` through `Mutate`. The draft is on disk before the commit, so a failed commit is retried (`POST /jobs///save`) and one a restart cut off is resumed (`Server.ResumeJobs`) without calling Claude again. Save funcs may therefore run twice for one draft. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network. +- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job of its own kind: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`), then `saveReview` commits `reviews/.md`. An unsaved draft keeps its recording; `discardReview` deletes it when a new review replaces the draft. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`. - **Concepts are the same shape, outside the problems.** `POST /concepts` has Claude explain a technique or pasted code (`internal/concept`) and commits `concepts//` (explanation, C++ snippet, the request). The slug is Claude's, so a new concept's job is keyed by an id and returns `{slug}` as its `Result`; rewrites are keyed by slug. The index reads them into `Index.Concepts`, and they are public. -- **Evaluations are the same shape, but commit nothing.** `POST /evaluate` judges the solve page's draft: it runs the saved tests on the runner, then asks Claude (`internal/evaluate`). It keeps the answer in memory as the job's `Result` (`explain.Jobs.StartWith`), and the page polls for it. +- **Evaluations are the same shape, but commit nothing.** `POST /evaluate` judges the solve page's draft: it runs the saved tests on the runner, then asks Claude (`internal/evaluate`). Its kind has no save func: the answer is the job's `Result`, kept in the job's record, and the page polls for it. + +- **Claude calls are metered.** `claude.Client` records every call's tokens in `usage.Ledger`; `Server.claudeReady` refuses a new Claude job with 429 once `CLAUDE_MONTHLY_BUDGET` is spent. A nil ledger tracks nothing, which the tests use. +- **Admin writes are same-origin only.** `auth.SameOrigin` runs before `auth.Require` on the admin group and refuses a cross-origin browser request (403). - **Code runs in a separate service, never in the site.** The solve page's run/lint handlers (`handlers/run.go`) read the problem from the clone (`Server.Dir`, not the index, which truncates) and post to `cmd/usacorunner` through `runner.Client`; `internal/runner/types.go` is the contract between them. Tests fake it with `handlers.Runner`. The runner's own tests run real g++/python3/clang-tidy/ruff and skip whichever is missing. @@ -30,3 +33,4 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al - **Edits look at the disk.** An edit func passed to `Mutate` may run twice, so it must locate the problem with `findOnDisk`, never from the index. - **Commit subjects match the CLI's** (`lib/cmd/done.sh`): "Solve " and so on. - **The problem layout belongs to the CLI** in the repo root (`lib/`). When the CLI's layout changes, update `internal/index`. +- **Docs are tested.** `docs_test.go` fails when README.md's route table and `Routes` disagree, or when a `./usaco` command in the root README is missing from `CliPage.vue` (skipped in CI, which only has `site/`). diff --git a/site/README.md b/site/README.md index 487e67b..3934c25 100644 --- a/site/README.md +++ b/site/README.md @@ -27,7 +27,9 @@ There is no database. The CLI's layout is the data model (see the root README.md The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into memory. -- **Reading.** A Gitea push webhook triggers a fetch and hard reset, then a re-index, so a `usaco done && usaco sync` is live in seconds. A pull every `PULL_INTERVAL` (10m) catches missed hooks. The clone is a cache: the remote always wins. +**The repo must stay private on Gitea.** The site hides `problem.md` (the judge's text) and `reviews/` (transcripts of the admin talking) from the public, but git holds both, so a public repo would publish them anyway. The server reads it with `GIT_TOKEN`, so it does not need the repo to be public. + +- **Reading.** A Gitea push webhook triggers a fetch and hard reset, then a re-index, so a `usaco done && usaco sync` is live in seconds. A pull every `PULL_INTERVAL` (10m) catches missed hooks. A sync that leaves HEAD where it was (the interval's pull, or the hook for the site's own push) skips the re-index. The clone is a cache: the remote always wins. - **Writing.** An admin edit runs under one lock: 1. sync 2. change the files @@ -95,14 +97,19 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro | `POST /usaco/api/concepts//explain` | admin | `{note?}`: rewrites the concept in place and answers 202; 409 if a rewrite is running | | `GET /usaco/api/concepts//explain` | admin | the latest rewrite job | | `DELETE /usaco/api/concepts/` | admin | removes `concepts//`, committed as "Forget concept " | +| `POST /usaco/api/jobs///save` | admin | commits an unsaved job's answer again (see "Background jobs"); answers 202 and the job, polled at its usual route. 404 if it has nothing unsaved, 409 while it runs | +| `GET /usaco/api/usage` | admin | the Claude spend: `{tracked, budget, month, months: [{name, calls, cost}], kinds}` | | `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull | | `GET /usaco/api/health` | open | 200 once the clone is indexed | +Every job status (`GET …/explain`, `…/review`, `…/evaluate`, `/concept-jobs/`, `/concepts//explain`) is `{kind, key, state: idle|running|done|error, error?, unsaved?, result?}`. Every route that starts a Claude job also answers 429 once this month's budget is spent (`CLAUDE_MONTHLY_BUDGET`), and 503 while the server is shutting down. + Auth works as in job-tracker: - `internal/auth` forwards the browser's cookies to the site backend's `/auth/validate-admin`. - A "yes" is cached for 30 seconds. - A refused admin action sends the browser to `/admin/login?redirect=…`. +- An admin route that changes something also refuses (403) a request the browser says came from another origin (`auth.SameOrigin`, by `Sec-Fetch-Site`, else `Origin`). The cookies are `SameSite=Lax`, which already keeps them off other sites' requests; this covers the rest of adam-french.co.uk. ## Development @@ -128,7 +135,7 @@ Every variable is listed and explained in `.env.example`. ## Running inside web_server -The site's `docker-compose.yml` runs the published image as service `usaco`, with an explicit `environment:` list. The site's nginx routes `/usaco/` to it. `./usaco-data` is mounted at `/data` and holds only the clone, so deleting it is safe: the next start re-clones. The container runs as uid 1000, so run `chown 1000 usaco-data` on the host. +The site's `docker-compose.yml` runs the published image as service `usaco`, with an explicit `environment:` list. The site's nginx routes `/usaco/` to it. `./usaco-data` is mounted at `/data` and holds the clone (`repo/`), the background jobs' records (`jobs/`) and the Claude spend ledger (`usage.jsonl`). Deleting it is safe: the next start re-clones. It costs any answer not yet committed, the last evaluations and the spend history. The container runs as uid 1000, so run `chown 1000 usaco-data` on the host. ### Deploying @@ -172,7 +179,7 @@ The Explain panel on a problem page (admin only) asks Claude for an intuitive ex - **Input.** The statement (`problem.md`; when it is missing, it is fetched from the link and saved too), up to three saved tests with outputs or the sample input, optionally the main solution file, and the admin's "where I'm stuck" note. - **Output.** A JSON-schema reply (`internal/explain` `Schema`): the key observation, 2 to 4 hints, the approach, a walkthrough whose steps each carry an SVG diagram, complexity, pitfalls and a pseudocode sketch. It is stored as markdown with one `## ` section each, and the page shows every section folded so the reader opens only as much as they need. Diagrams are ```` ```svg ```` fences, sanitized with DOMPurify before they are inserted. -- **The call.** `CLAUDE_MODEL` (default `claude-opus-5-5`) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job, because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines. +- **The call.** `CLAUDE_MODEL` (default `claude-opus-5-5`) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job (see "Background jobs"), because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines and kept in the spend ledger (see "Claude spend"). - **Statements.** LeetCode and USACO can be fetched. Codeforces sits behind a Cloudflare challenge, and other judges are unknown, so paste those. ## Concepts @@ -193,25 +200,39 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex - **Transcription.** Claude cannot take audio, so the recording goes first to an OpenAI-compatible `/v1/audio/transcriptions` endpoint: `TRANSCRIBE_URL` (default the OpenAI API) with `TRANSCRIBE_MODEL` (default `whisper-1`, about $0.006 a minute). It asks for word and segment timestamps, and for a verbatim transcript, because Whisper otherwise drops the fillers. A self-hosted faster-whisper server works by changing the URL. - **Metrics.** Pace (words per minute), pauses of 2 seconds or more, filler-word counts and when complexity was first mentioned are measured from the timestamps (`transcribe.Metrics`), since Claude never hears the recording. It is told so, and judges delivery from the words and these numbers only, not tone. - **Review.** The statement, examples, optionally the main solution file, the admin's note, the metrics and the timestamped transcript go to Claude with a JSON schema (`internal/review` `Schema`): a verdict (correct, partly correct, incorrect, incomplete), a restatement, an assessment of the approach and complexities, missed edge cases, delivery feedback quoting `[mm:ss]`, 1 to 5 scores in five areas, strengths and things to work on. The markdown ends with the metrics and the full transcript. Its first line is a `` comment the index reads. -- **The recording.** It is too big for git. With all five `S3_*` variables set it is kept in that bucket as `/.` and the page gets a player; otherwise it is thrown away once transcribed. In web_server that is a private Garage bucket, never the public `uploads` one. A recording whose review fails is deleted again. +- **The recording.** It is too big for git. With all five `S3_*` variables set it is kept in that bucket as `/.` and the page gets a player; otherwise it is thrown away once transcribed. In web_server that is a private Garage bucket, never the public `uploads` one. A recording whose review could not be written is deleted again. One whose review was written but not committed stays with the unsaved review, until it is saved or a new recording replaces it. - **Privacy.** A review is a transcript of the admin talking, so reviews and their count are blanked for everyone else, even on solved problems. ## Solve page `/usaco/p//solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Evaluate (Claude), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`. -- **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it. +- **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs solutions. The one script it runs is the clone's `lib/leetcode.py` (the LeetCode import), with an environment holding none of those secrets (`leetcode.scriptEnv`). `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it. - **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `.in` with that file also on stdin, `.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s. - **Autocomplete** is in the browser (`web/src/completions.js`), since `@codemirror/lang-cpp` has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after `.` and `->`, and snippets (`for`, `forr`, `foreach`, `lambda`, `dfs`, `sortby`...). Python adds the contest standard library (`heapq`, `bisect`, `collections`...) and members after `.` to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner. - **Vim keys** are a checkbox in the toolbar (`@replit/codemirror-vim`), off by default and remembered in the browser. A status line under the editor shows the mode and the command being typed, and `:w` saves as Save does. Run and Submit keep their Ctrl+Enter keys in every mode. -- **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result lives in the server's memory until the next evaluation or a restart. A statement it had to fetch is not saved either. +- **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result is the job's, kept until the next evaluation of the problem. A statement it had to fetch is not saved either. - **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22). +## Background jobs + +Explanations, concepts, reviews and evaluations take minutes, so each is a job (`internal/jobs`) that the page polls. One job runs per kind and key at a time: per problem, per concept slug, or per new-concept id. + +- **Work, then save.** A job that commits runs in two steps. The work (statement fetch, transcription, Claude) produces a draft, and the draft is written to `$DATA_DIR/jobs//.json` before the commit. If the commit fails (the push was rejected twice, or Gitea is down), the job ends as an error with `unsaved: true`, and the page offers **Save again**, which commits the same draft without asking Claude again. +- **Restarts.** Records survive a restart, so a finished job's status and an evaluation's result are still there afterwards. On SIGTERM the server stops taking new jobs (503) and waits up to `SHUTDOWN_GRACE` (5m) for running ones, still answering the pages that poll them. web_server's `stop_grace_period` for `usaco` must be longer. A job cut off anyway is settled on the next start. Mid-commit, its draft is saved again once the first sync is done. Still at its work, it is marked as interrupted, and must be started again. +- **Records are pruned** a week after they finish, unless they hold an unsaved draft. + +## Claude spend + +Every Claude call is appended to `$DATA_DIR/usage.jsonl` (`internal/usage`) with its tokens and an estimated cost. The estimate uses the answering model's list price, which can be a fallback model. A refused or cut-off call is billed too, so it is recorded too. The stats page shows the admin this month's total, the months before it, and the split by feature. Transcription is not counted; it costs about $0.006 a minute. + +`CLAUDE_MONTHLY_BUDGET` (dollars, unset for none) caps a calendar month (UTC). Once the month's estimate reaches it, new jobs are refused with 429 until the 1st. A job already running is never stopped, so a month can end slightly over. + ## Things that are easy to get wrong - **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time. - **Edits must decide from disk, not the index.** `repo.Mutate` may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with `findOnDisk`. - **`problem.md` is the judge's text.** `GET /problems/` blanks it for non-admins, so the public site links to the judge instead of republishing it. -- **An explanation, review or evaluation job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again). +- **A save func may run twice for one draft.** A restart after the push but before the job's record says so resumes the save. Explanations and reviews rewrite the same file, so the second run commits nothing. A new concept looks for itself first (`newConceptSlug`). - **Uploads are capped at 25 MB**, the OpenAI API's limit. nginx's server-wide `client_max_body_size 50M` is above it; lowering that below 25M would turn big recordings into nginx 413s. - **`tests/*.out` used to be gitignored** by the root `*.out` rule. The root `.gitignore` now re-includes `**/tests/*.out`. A test whose expected output is shown as "Not saved." predates that change or never had one. diff --git a/site/cmd/usacosite/main.go b/site/cmd/usacosite/main.go index 2f0ad94..69f5f6e 100644 --- a/site/cmd/usacosite/main.go +++ b/site/cmd/usacosite/main.go @@ -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 { diff --git a/site/docs_test.go b/site/docs_test.go new file mode 100644 index 0000000..c88bc19 --- /dev/null +++ b/site/docs_test.go @@ -0,0 +1,86 @@ +// Package docs_test checks the hand-written documentation against what it +// describes, so the two cannot drift apart unnoticed. +package docs_test + +import ( + "os" + "regexp" + "sort" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/handlers" +) + +// README.md's route table lists every API route, and nothing else. +func TestReadmeRoutes(t *testing.T) { + b, err := os.ReadFile("README.md") + if err != nil { + t.Fatal(err) + } + row := regexp.MustCompile("(?m)^\\| `(GET|POST|PUT|DELETE) /usaco/api([^`?]*)") + param := regexp.MustCompile(`<([a-z]+)>`) + documented := map[string]bool{} + for _, m := range row.FindAllStringSubmatch(string(b), -1) { + documented[m[1]+" "+param.ReplaceAllString(m[2], ":$1")] = true + } + + gin.SetMode(gin.TestMode) + r := gin.New() + (&handlers.Server{}).Routes(r.Group("/usaco/api")) + served := map[string]bool{} + for _, rt := range r.Routes() { + served[rt.Method+" "+strings.TrimPrefix(rt.Path, "/usaco/api")] = true + } + + for _, missing := range diff(served, documented) { + t.Errorf("README.md's route table is missing %s", missing) + } + for _, stale := range diff(documented, served) { + t.Errorf("README.md documents %s, which is not served", stale) + } +} + +// The CLI page (web/src/views/CliPage.vue) is a condensed copy of the root +// README's commands, since the image's build context cannot reach the +// README. Every command there must be on the page. CI exports only site/, +// so there this is skipped; `make check` in a full checkout runs it. +func TestCliPageCoversTheCommands(t *testing.T) { + readme, err := os.ReadFile("../README.md") + if os.IsNotExist(err) { + t.Skip("no root README (CI builds site/ alone)") + } + if err != nil { + t.Fatal(err) + } + page, err := os.ReadFile("web/src/views/CliPage.vue") + if err != nil { + t.Fatal(err) + } + // Commands the page gives as another one's alias. + aliases := map[string]string{"vim": "(also vim, edit)"} + for _, m := range regexp.MustCompile(`(?m)^\./usaco ([a-z]+)`).FindAllStringSubmatch(string(readme), -1) { + cmd := m[1] + want := "usaco " + cmd + if a, ok := aliases[cmd]; ok { + want = a + } + if !strings.Contains(string(page), want) { + t.Errorf("CliPage.vue does not mention %q (README.md has ./usaco %s)", want, cmd) + } + } +} + +// diff is the keys of a that are not in b, sorted. +func diff(a, b map[string]bool) []string { + var out []string + for k := range a { + if !b[k] { + out = append(out, k) + } + } + sort.Strings(out) + return out +} diff --git a/site/internal/auth/origin.go b/site/internal/auth/origin.go new file mode 100644 index 0000000..4cc0d67 --- /dev/null +++ b/site/internal/auth/origin.go @@ -0,0 +1,57 @@ +package auth + +import ( + "net/http" + "net/url" + + "github.com/gin-gonic/gin" +) + +// SameOrigin refuses a state-changing request that a browser made from +// another origin: cross-site request forgery. +// +// The admin is recognized by cookies alone, and the site's cookies are +// SameSite=Lax, which keeps them off another site's POST. That is the main +// defence; this is the second. Lax still sends them from any other origin of +// the same site (another subdomain of adam-french.co.uk), and the JSON +// handlers would decode a text/plain form body too, so the browser's own +// word on where a request came from is checked as well. +// +// Sec-Fetch-Site is set by every current browser and cannot be set by a +// page. An older browser sends Origin on a cross-origin POST instead, which +// must name this host (nginx passes the browser's Host through). A request +// with neither is not from a browser (curl, the tests), and so carries no +// one's cookies but its sender's. +// +// Same-origin pages are not told apart: Gitea, at /gitea/ on the same host, +// is trusted like this site's own pages. +func SameOrigin() gin.HandlerFunc { + return func(ctx *gin.Context) { + r := ctx.Request + switch r.Method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + ctx.Next() + return + } + if site := r.Header.Get("Sec-Fetch-Site"); site != "" { + // "none" is a request the user made themselves (the address + // bar), which a page cannot forge. + if site != "same-origin" && site != "none" { + refuse(ctx) + return + } + } else if origin := r.Header.Get("Origin"); origin != "" { + if u, err := url.Parse(origin); err != nil || u.Host != r.Host { + refuse(ctx) + return + } + } + ctx.Next() + } +} + +// refuse is a 403, not the 401 that sends the page to the login: logging in +// would not help. +func refuse(ctx *gin.Context) { + ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"}) +} diff --git a/site/internal/auth/origin_test.go b/site/internal/auth/origin_test.go new file mode 100644 index 0000000..1df8f01 --- /dev/null +++ b/site/internal/auth/origin_test.go @@ -0,0 +1,43 @@ +package auth + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestSameOrigin(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(SameOrigin()) + r.Any("/x", func(ctx *gin.Context) { ctx.Status(http.StatusOK) }) + + cases := []struct { + name, method string + headers map[string]string + want int + }{ + {"same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200}, + {"typed in", "POST", map[string]string{"Sec-Fetch-Site": "none"}, 200}, + {"sibling subdomain", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403}, + {"another site", "PUT", map[string]string{"Sec-Fetch-Site": "cross-site", "Origin": "https://example.com"}, 403}, + {"cross-site GET", "GET", map[string]string{"Sec-Fetch-Site": "cross-site"}, 200}, + {"old browser, same host", "POST", map[string]string{"Origin": "https://adam-french.co.uk"}, 200}, + {"old browser, other host", "DELETE", map[string]string{"Origin": "https://evil.adam-french.co.uk"}, 403}, + {"not a browser", "POST", nil, 200}, + } + for _, tc := range cases { + req := httptest.NewRequest(tc.method, "/x", nil) + req.Host = "adam-french.co.uk" + for k, v := range tc.headers { + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + if rec.Code != tc.want { + t.Errorf("%s: %d, want %d", tc.name, rec.Code, tc.want) + } + } +} diff --git a/site/internal/claude/claude.go b/site/internal/claude/claude.go index 0155cd7..484baf5 100644 --- a/site/internal/claude/claude.go +++ b/site/internal/claude/claude.go @@ -16,10 +16,13 @@ import ( "errors" "fmt" "log" + "time" "github.com/anthropics/anthropic-sdk-go" "github.com/anthropics/anthropic-sdk-go/option" "github.com/anthropics/anthropic-sdk-go/shared/constant" + + "adam-french.co.uk/usaco-site/internal/usage" ) // DefaultModel is used when CLAUDE_MODEL is blank. @@ -40,6 +43,9 @@ func (f *Failure) Unwrap() error { return f.Err } // Request is one call. type Request struct { + // Tag names the feature making the call ("explain", "review"...) in + // the usage ledger. + Tag string System string User string Schema map[string]any @@ -50,6 +56,8 @@ type Request struct { type Client struct { api anthropic.Client model string + // Ledger records what each call cost; nil records nothing. + Ledger *usage.Ledger } // New builds a client, or returns ErrNotConfigured for a blank key. opts @@ -102,12 +110,20 @@ func (c *Client) JSON(ctx context.Context, req Request, out any) error { } } if err := stream.Err(); err != nil { + // A stream that broke off partway was still billed for what it + // produced. + if msg.Usage.OutputTokens > 0 { + c.record(req.Tag, msg) + } return apiFailure(err) } u := msg.Usage log.Printf("[claude] %s: %d in (%d cached, %d written), %d out, stop %s", msg.Model, u.InputTokens, u.CacheReadInputTokens, u.CacheCreationInputTokens, u.OutputTokens, msg.StopReason) + // Recorded before the stop reason is looked at: a refusal or a reply + // cut off at the length limit is billed all the same. + c.record(req.Tag, msg) switch msg.StopReason { case anthropic.BetaStopReasonRefusal: @@ -128,6 +144,18 @@ func (c *Client) JSON(ctx context.Context, req Request, out any) error { return &Failure{"Claude's reply was empty", errors.New("no text block")} } +func (c *Client) record(tag string, msg anthropic.BetaMessage) { + u := msg.Usage + model := string(msg.Model) + if model == "" { + model = c.model + } + c.Ledger.Record(usage.Entry{ + Time: time.Now(), Kind: tag, Model: model, + In: u.InputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens, Out: u.OutputTokens, + }) +} + func apiFailure(err error) error { if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { return &Failure{"Claude took too long", err} diff --git a/site/internal/claude/claude_test.go b/site/internal/claude/claude_test.go index 35dbacb..9386f5a 100644 --- a/site/internal/claude/claude_test.go +++ b/site/internal/claude/claude_test.go @@ -8,10 +8,14 @@ import ( "io" "net/http" "net/http/httptest" + "path/filepath" "strings" "testing" + "time" "github.com/anthropics/anthropic-sdk-go/option" + + "adam-french.co.uk/usaco-site/internal/usage" ) // sse is a minimal streamed reply: one text block holding text. @@ -111,3 +115,21 @@ func TestFailures(t *testing.T) { } } } + +// Every answered call is in the ledger, a refusal included: it is billed. +func TestLedger(t *testing.T) { + l, err := usage.Open(filepath.Join(t.TempDir(), "usage.jsonl"), 0) + if err != nil { + t.Fatal(err) + } + for _, stop := range []string{"end_turn", "refusal"} { + c := fake(t, 200, sse(`{"a":"hi"}`, stop), nil, nil) + c.Ledger = l + var out map[string]any + c.JSON(context.Background(), Request{Tag: "explain", System: "s", User: "u", Schema: map[string]any{}, MaxTokens: 10}, &out) + } + s := l.Summarize(time.Now()) + if len(s.Kinds) != 1 || s.Kinds[0].Name != "explain" || s.Kinds[0].Calls != 2 || s.Month <= 0 { + t.Fatalf("summary = %+v", s) + } +} diff --git a/site/internal/concept/concept.go b/site/internal/concept/concept.go index 4f4630c..3e41cb1 100644 --- a/site/internal/concept/concept.go +++ b/site/internal/concept/concept.go @@ -153,7 +153,7 @@ func Prompt(in Input) string { // taken; the caller picks the one to save under and passes it to Files. func Generate(ctx context.Context, a explain.Asker, in Input) (Result, error) { var r Result - err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + err := a.JSON(ctx, claude.Request{Tag: "concept", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) if err != nil { return Result{}, err } diff --git a/site/internal/evaluate/evaluate.go b/site/internal/evaluate/evaluate.go index 5bc39ae..604516a 100644 --- a/site/internal/evaluate/evaluate.go +++ b/site/internal/evaluate/evaluate.go @@ -4,8 +4,8 @@ // there a small input that breaks it. // // The code is a draft, so unlike an explanation or a review nothing is -// committed. The answer is kept in memory with the source it judged -// (explain.Jobs.StartWith), and the page anchors each issue to its line in +// committed. The answer is kept as the job's result with the source it judged +// (a jobs.Kind with no save), and the page anchors each issue to its line in // the editor. // // Claude is given the saved tests' verdicts from the runner along with the @@ -285,7 +285,7 @@ func capped(s string, n int) string { // Generate asks Claude and returns the evaluation. func Generate(ctx context.Context, a explain.Asker, in Input, now time.Time) (*Evaluation, error) { var r Result - err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + err := a.JSON(ctx, claude.Request{Tag: "evaluate", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) if err != nil { return nil, err } diff --git a/site/internal/explain/explain.go b/site/internal/explain/explain.go index dc9dd00..acca9dd 100644 --- a/site/internal/explain/explain.go +++ b/site/internal/explain/explain.go @@ -147,7 +147,7 @@ func Prompt(in Input) string { // Generate asks Claude and returns explain.md. func Generate(ctx context.Context, a Asker, in Input, now time.Time) (string, error) { var r Result - err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + err := a.JSON(ctx, claude.Request{Tag: "explain", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) if err != nil { return "", err } diff --git a/site/internal/explain/explain_test.go b/site/internal/explain/explain_test.go index 5f1ba15..83eede8 100644 --- a/site/internal/explain/explain_test.go +++ b/site/internal/explain/explain_test.go @@ -105,37 +105,3 @@ func TestGenerate(t *testing.T) { t.Error("System is missing the rules it shares with concepts") } } - -func TestJobsOneAtATime(t *testing.T) { - var j Jobs - if s := j.Get("a"); s.State != Idle { - t.Fatalf("fresh state = %q, want idle", s.State) - } - release := make(chan struct{}) - if !j.Start("a", func() error { <-release; return nil }) { - t.Fatal("first start refused") - } - if j.Start("a", func() error { return nil }) { - t.Fatal("second start while running accepted") - } - if !j.Start("b", func() error { return context.Canceled }) { - t.Fatal("another problem's job refused") - } - close(release) - wait := func(name string) Status { - for range 200 { - if s := j.Get(name); s.State != Running { - return s - } - time.Sleep(5 * time.Millisecond) - } - t.Fatalf("%s still running", name) - return Status{} - } - if s := wait("a"); s.State != Done || s.Finished == nil { - t.Errorf("a = %+v, want done", s) - } - if s := wait("b"); s.State != Failed || s.Error != context.Canceled.Error() { - t.Errorf("b = %+v, want the error", s) - } -} diff --git a/site/internal/explain/jobs.go b/site/internal/explain/jobs.go deleted file mode 100644 index fa4c05c..0000000 --- a/site/internal/explain/jobs.go +++ /dev/null @@ -1,78 +0,0 @@ -package explain - -import ( - "sync" - "time" -) - -// A job's states. Idle means nothing has run since the server started. -const ( - Idle = "idle" - Running = "running" - Done = "done" - Failed = "error" -) - -// Status is what the page polls for. -type Status struct { - 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 StartWith job's answer. - Result any `json:"result,omitempty"` -} - -// Jobs runs at most one explanation per problem at a time. An explanation -// takes a minute or more, longer than nginx waits for a response, so the -// request only starts it and the page polls. State is in memory: a restart -// mid-job loses the job, and nothing is committed until it finishes. -type Jobs struct { - mu sync.Mutex - m map[string]*Status -} - -// Start runs fn in the background unless a job for name is running, and -// reports whether it started. fn's error is shown to the admin, so it must -// be a message meant for them. -func (j *Jobs) Start(name string, fn func() error) bool { - return j.StartWith(name, func() (any, error) { return nil, fn() }) -} - -// StartWith is Start for a job whose answer is kept here rather than -// committed: a done job's Status carries it until the next job for name -// starts, or the server restarts. -func (j *Jobs) StartWith(name string, fn func() (any, error)) bool { - j.mu.Lock() - defer j.mu.Unlock() - if j.m == nil { - j.m = map[string]*Status{} - } - if s := j.m[name]; s != nil && s.State == Running { - return false - } - now := time.Now() - j.m[name] = &Status{State: Running, Started: &now} - go func() { - res, err := fn() - j.mu.Lock() - defer j.mu.Unlock() - end := time.Now() - s := &Status{State: Done, Started: &now, Finished: &end, Result: res} - if err != nil { - s.State, s.Error, s.Result = Failed, err.Error(), nil - } - j.m[name] = s - }() - return true -} - -// Get is name's latest job. -func (j *Jobs) Get(name string) Status { - j.mu.Lock() - defer j.mu.Unlock() - if s := j.m[name]; s != nil { - return *s - } - return Status{State: Idle} -} diff --git a/site/internal/handlers/concept.go b/site/internal/handlers/concept.go index 0357f21..ea7a3f6 100644 --- a/site/internal/handlers/concept.go +++ b/site/internal/handlers/concept.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "encoding/json" "errors" "fmt" "log" @@ -78,8 +79,7 @@ const maxConceptCode = 32 << 10 // choose, so the job is keyed by an id of its own, which the page polls // until the result names the slug to open. func (s *Server) startConcept(ctx *gin.Context) { - if s.Claude == nil { - ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + if !s.claudeReady(ctx) { return } idx := s.Index() @@ -110,11 +110,9 @@ func (s *Server) startConcept(ctx *gin.Context) { in := concept.Input{Topic: topic, Code: body.Code, Existing: conceptRefs(idx, "")} // Microseconds, so two requests in one second are two jobs. id := time.Now().UTC().Format("2006-01-02-150405.000000") - if !s.newConceptJobs.StartWith(id, func() (any, error) { return s.writeConcept(in, "") }) { - ctx.JSON(http.StatusConflict, gin.H{"error": "that concept is already being explained"}) - return + if startJob(ctx, s.newConceptJobs, id, "that concept is already being explained", func() (any, error) { return s.writeConcept(in, "") }) { + ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)}) } - ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)}) } func (s *Server) newConceptStatus(ctx *gin.Context) { @@ -132,8 +130,7 @@ func (s *Server) rewriteConcept(ctx *gin.Context) { if !ok { return } - if s.Claude == nil { - ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + if !s.claudeReady(ctx) { return } var body rewriteBody @@ -155,11 +152,9 @@ func (s *Server) rewriteConcept(ctx *gin.Context) { } in := concept.Input{Topic: topic, Code: code, Previous: prev, Note: body.Note, Existing: conceptRefs(s.Index(), c.Slug)} slug := c.Slug - if !s.conceptJobs.StartWith(slug, func() (any, error) { return s.writeConcept(in, slug) }) { - ctx.JSON(http.StatusConflict, gin.H{"error": "this concept is already being rewritten"}) - return + if startJob(ctx, s.conceptJobs, slug, "this concept is already being rewritten", func() (any, error) { return s.writeConcept(in, slug) }) { + ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug)) } - ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug)) } func (s *Server) rewriteStatus(ctx *gin.Context) { @@ -186,9 +181,20 @@ type conceptResult struct { Slug string `json:"slug"` } -// writeConcept is one job: a new concept when slug is empty, else a rewrite -// of that one. Its error is shown to the admin, so every path returns a -// message meant for them and logs the detail. +// conceptDraft is a written concept waiting to be committed. Slug is set +// for a rewrite; a new concept's is picked when it is saved. +type conceptDraft struct { + Slug string `json:"slug,omitempty"` + Result concept.Result `json:"result"` + Topic string `json:"topic"` + Code string `json:"code,omitempty"` + Model string `json:"model"` + Written time.Time `json:"written"` +} + +// writeConcept is one job's work: a new concept when slug is empty, else a +// rewrite of that one. Its error is shown to the admin, so every path +// returns a message meant for them and logs the detail. func (s *Server) writeConcept(in concept.Input, slug string) (any, error) { ctx, cancel := context.WithTimeout(context.Background(), explainTimeout) defer cancel() @@ -203,21 +209,34 @@ func (s *Server) writeConcept(in concept.Input, slug string) (any, error) { log.Printf("[concept] %s: %v", in.Topic, err) return nil, errors.New("the explanation could not be written") } + return conceptDraft{Slug: slug, Result: r, Topic: in.Topic, Code: in.Code, Model: s.Claude.Model(), Written: time.Now()}, nil +} - rewrite := slug != "" - if !rewrite { - slug = freeSlug(s.Index(), r.Slug) +// saveConcept commits a concept and answers where it is now. +func (s *Server) saveConcept(raw json.RawMessage) (any, error) { + var d conceptDraft + if err := json.Unmarshal(raw, &d); err != nil { + return nil, err } - files := concept.Files(r, in, slug, s.Claude.Model(), time.Now()) - err = s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error { + slug, rewrite := d.Slug, d.Slug != "" + if !rewrite { + var saved bool + if slug, saved = newConceptSlug(s.Index(), d); saved { + return conceptResult{Slug: slug}, nil + } + } + ctx, cancel := context.WithTimeout(context.Background(), saveTimeout) + defer cancel() + files := concept.Files(d.Result, concept.Input{Topic: d.Topic, Code: d.Code}, slug, d.Model, d.Written) + err := s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error { cdir := filepath.Join(dir, index.Concepts, slug) _, err := os.Stat(cdir) switch { case rewrite && os.IsNotExist(err): return &requestError{http.StatusNotFound, "the concept was deleted while Claude was writing"} case !rewrite && err == nil: - // Saved since the slug was picked; the next try picks another. - return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; try again", slug)} + // Saved since the slug was picked; saving again picks another. + return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; save again to pick another name", slug)} } if err := os.MkdirAll(cdir, 0o755); err != nil { return err @@ -235,14 +254,23 @@ func (s *Server) writeConcept(in concept.Input, slug string) (any, error) { return conceptResult{Slug: slug}, nil } -// freeSlug is want, or want-2, want-3... if a concept already has it. A -// new question never overwrites a saved concept; rewriting one is its own -// request. -func freeSlug(idx *index.Index, want string) string { - slug := want +// newConceptSlug is the name Claude gave the concept, or name-2, name-3... +// if a concept already has it: a new question never overwrites a saved +// concept, and rewriting one is its own request. saved reports that the +// concept under slug is this very draft (the same question, and the same +// snippet in Claude's own words), which a save run again after a restart that came after its push +// finds, and must not save a second time. +func newConceptSlug(idx *index.Index, d conceptDraft) (slug string, saved bool) { + want, req := d.Result.Slug, strings.TrimSpace(concept.Request(d.Topic, d.Code)) + slug = want for n := 2; ; n++ { - if _, taken := idx.Concepts[slug]; !taken { - return slug + c, taken := idx.Concepts[slug] + if !taken { + return slug, false + } + if strings.TrimSpace(c.Request) == req && c.Snippet != nil && + strings.TrimSpace(c.Snippet.Content) == strings.TrimSpace(concept.Snippet(d.Result.Snippet, slug)) { + return slug, true } slug = fmt.Sprintf("%s-%d", want, n) } diff --git a/site/internal/handlers/concept_test.go b/site/internal/handlers/concept_test.go index 399c23f..f057c51 100644 --- a/site/internal/handlers/concept_test.go +++ b/site/internal/handlers/concept_test.go @@ -13,7 +13,7 @@ import ( "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/concept" - "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/jobs" ) // fakeConceptClaude explains everything as a Fenwick tree. If gate is set, @@ -36,19 +36,19 @@ func (f *fakeConceptClaude) JSON(_ context.Context, req claude.Request, out any) return nil } -func waitStatus(t *testing.T, r *gin.Engine, path string) explain.Status { +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 explain.Status + var s jobs.Status json.Unmarshal(rec.Body.Bytes(), &s) - if s.State != explain.Running { + if s.State != jobs.Running { return s } time.Sleep(5 * time.Millisecond) } t.Fatalf("%s still running", path) - return explain.Status{} + return jobs.Status{} } // newConcept starts a concept and returns the slug its job saved it under. @@ -61,7 +61,7 @@ func newConcept(t *testing.T, r *gin.Engine, body string) string { var started struct{ ID string } json.Unmarshal(rec.Body.Bytes(), &started) s := waitStatus(t, r, "/usaco/api/concept-jobs/"+started.ID) - if s.State != explain.Done { + if s.State != jobs.Done { t.Fatalf("job = %+v, want done", s) } res, _ := s.Result.(map[string]any) @@ -172,7 +172,7 @@ func TestConceptRewrite(t *testing.T) { t.Fatalf("second rewrite while running = %d, want 409", rec.Code) } close(fc.gate) - if s := waitStatus(t, r, path); s.State != explain.Done { + if s := waitStatus(t, r, path); s.State != jobs.Done { t.Fatalf("rewrite job = %+v", s) } for _, want := range []string{"\nhelp explain fenwick trees", "\n# Fenwick tree", "## Snippet", "\nstep 2 is wrong"} { diff --git a/site/internal/handlers/evaluate.go b/site/internal/handlers/evaluate.go index 21e7655..821503e 100644 --- a/site/internal/handlers/evaluate.go +++ b/site/internal/handlers/evaluate.go @@ -23,8 +23,7 @@ const evaluateTimeout = 10 * time.Minute // committed: the source is a draft, and the answer is about this version of // it only. func (s *Server) startEvaluate(ctx *gin.Context) { - if s.Claude == nil { - ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + if !s.claudeReady(ctx) { return } body, p, l, ok := s.readCode(ctx) @@ -48,11 +47,9 @@ func (s *Server) startEvaluate(ctx *gin.Context) { Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note, } link := p.URL - if !s.evalJobs.StartWith(p.Name, func() (any, error) { return s.evaluate(in, link, l) }) { - ctx.JSON(http.StatusConflict, gin.H{"error": "a solution is already being evaluated"}) - return + if startJob(ctx, s.evalJobs, p.Name, "a solution is already being evaluated", func() (any, error) { return s.evaluate(in, link, l) }) { + ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name)) } - ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name)) } func (s *Server) evaluateStatus(ctx *gin.Context) { diff --git a/site/internal/handlers/evaluate_test.go b/site/internal/handlers/evaluate_test.go index cbe0b41..2ebec7b 100644 --- a/site/internal/handlers/evaluate_test.go +++ b/site/internal/handlers/evaluate_test.go @@ -12,7 +12,7 @@ import ( "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/evaluate" - "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/jobs" ) // fakeEvaluator flags line 1 of whatever it is shown, or fails. @@ -45,7 +45,7 @@ func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus { for range 400 { var s evalStatus json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s) - if s.State != explain.Running { + if s.State != jobs.Running { return s } time.Sleep(5 * time.Millisecond) @@ -91,7 +91,7 @@ func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) { t.Fatalf("evaluate = %d %s", rec.Code, rec.Body) } s := waitEvaluate(t, r, "moocast") - if s.State != explain.Done || s.Result == nil { + if s.State != jobs.Done || s.Result == nil { t.Fatalf("job = %+v", s) } ev := s.Result @@ -124,7 +124,7 @@ func TestEvaluateWithoutARunner(t *testing.T) { // A runner that fails costs the verdicts, not the evaluation. fr.err = errors.New("runner down") do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) - if s := waitEvaluate(t, r, "moocast"); s.State != explain.Done || s.Result.Tests != "The tests were not run: the code runner failed." { + if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Done || s.Result.Tests != "The tests were not run: the code runner failed." { t.Fatalf("with a failing runner = %+v", s) } @@ -134,13 +134,13 @@ func TestEvaluateWithoutARunner(t *testing.T) { } do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) s := waitEvaluate(t, r, "moocast") - if s.State != explain.Done || !strings.Contains(fc.user, "the code runner is not configured") { + if s.State != jobs.Done || !strings.Contains(fc.user, "the code runner is not configured") { t.Fatalf("with no runner = %+v\n%s", s, fc.user) } fc.fail = true do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) - if s := waitEvaluate(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" || s.Result != nil { + if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" || s.Result != nil { t.Fatalf("a failed evaluation = %+v", s) } } diff --git a/site/internal/handlers/explain.go b/site/internal/handlers/explain.go index e5fef3d..ed03e91 100644 --- a/site/internal/handlers/explain.go +++ b/site/internal/handlers/explain.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "encoding/json" "errors" "fmt" "log" @@ -82,8 +83,7 @@ func (s *Server) startExplain(ctx *gin.Context) { if !ok { return } - if s.Claude == nil { - ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + if !s.claudeReady(ctx) { return } var body explainBody @@ -105,28 +105,33 @@ func (s *Server) startExplain(ctx *gin.Context) { in.Code = mainFile(p) } link := p.URL - if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) { - ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"}) - return + if startJob(ctx, s.explainJobs, p.Name, "an explanation is already being written", func() (any, error) { return s.explain(in, link) }) { + ctx.JSON(http.StatusAccepted, s.explainJobs.Get(p.Name)) } - ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name)) } func (s *Server) explainStatus(ctx *gin.Context) { if p, ok := s.lookup(ctx, true); ok { - ctx.JSON(http.StatusOK, s.jobs.Get(p.Name)) + ctx.JSON(http.StatusOK, s.explainJobs.Get(p.Name)) } } -// explain is one job. Its error is shown to the admin, so every path returns -// a message meant for them and logs the detail. -func (s *Server) explain(in explain.Input, link string) error { +// explainDraft is a written explanation waiting to be committed. +type explainDraft struct { + Name string `json:"name"` + Fetched string `json:"fetched,omitempty"` + Markdown string `json:"markdown"` +} + +// explain is one job's work. Its error is shown to the admin, so every path +// returns a message meant for them and logs the detail. +func (s *Server) explain(in explain.Input, link string) (any, error) { ctx, cancel := context.WithTimeout(context.Background(), explainTimeout) defer cancel() fetched, err := s.ensureStatement(ctx, "explain", in.Name, &in.Statement, link) if err != nil { - return err + return nil, err } md, err := explain.Generate(ctx, s.Claude, in, time.Now()) @@ -134,25 +139,35 @@ func (s *Server) explain(in explain.Input, link string) error { var f *claude.Failure if errors.As(err, &f) { log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err) - return f + return nil, f } log.Printf("[explain] %s: %v", in.Name, err) - return errors.New("the explanation could not be written") + return nil, errors.New("the explanation could not be written") } + return explainDraft{Name: in.Name, Fetched: fetched, Markdown: md}, nil +} - name := in.Name - err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error { - status, err := findOnDisk(dir, name) +// saveExplain commits an explanation. Running it again for a draft already +// pushed changes nothing, so commits nothing. +func (s *Server) saveExplain(raw json.RawMessage) (any, error) { + var d explainDraft + if err := json.Unmarshal(raw, &d); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), saveTimeout) + defer cancel() + err := s.Repo.Mutate(ctx, "Explain "+d.Name, func(dir string) error { + status, err := findOnDisk(dir, d.Name) if err != nil { return err } - pdir := filepath.Join(dir, status, name) - if err := saveFetched(pdir, fetched); err != nil { + pdir := filepath.Join(dir, status, d.Name) + if err := saveFetched(pdir, d.Fetched); err != nil { return err } - return writeOrRemove(filepath.Join(pdir, "explain.md"), md) + return writeOrRemove(filepath.Join(pdir, "explain.md"), d.Markdown) }) - return jobSaveError("explain", name, "the explanation was written but could not be saved to git", err) + return nil, jobSaveError("explain", d.Name, "the explanation was written but could not be saved to git", err) } // ensureStatement fetches the statement when none is saved, so a job can diff --git a/site/internal/handlers/explain_test.go b/site/internal/handlers/explain_test.go index fa759f0..6322cfc 100644 --- a/site/internal/handlers/explain_test.go +++ b/site/internal/handlers/explain_test.go @@ -13,6 +13,7 @@ import ( "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/jobs" "adam-french.co.uk/usaco-site/internal/statement" ) @@ -43,19 +44,19 @@ func (fakeJudge) Fetch(_ context.Context, link string) (string, error) { return "", statement.ErrUnsupported } -func waitJob(t *testing.T, r *gin.Engine, name string) explain.Status { +func waitJob(t *testing.T, r *gin.Engine, name string) jobs.Status { t.Helper() for range 400 { rec := do(r, "GET", "/usaco/api/problems/"+name+"/explain", "", true) - var s explain.Status + var s jobs.Status json.Unmarshal(rec.Body.Bytes(), &s) - if s.State != explain.Running { + if s.State != jobs.Running { return s } time.Sleep(5 * time.Millisecond) } t.Fatal("job still running") - return explain.Status{} + return jobs.Status{} } func TestExplainNeedsClaudeAndAStatement(t *testing.T) { @@ -87,7 +88,7 @@ func TestExplainWritesAndCommits(t *testing.T) { t.Fatalf("second start while running = %d, want 409", rec.Code) } close(fc.gate) - if s := waitJob(t, r, "moocast"); s.State != explain.Done { + if s := waitJob(t, r, "moocast"); s.State != jobs.Done { t.Fatalf("job = %+v, want done", s) } @@ -124,13 +125,13 @@ func TestExplainFetchesAMissingStatement(t *testing.T) { do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://cses.fi/x"}`, true) do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true) - if s := waitJob(t, r, "watermelon"); s.State != explain.Failed || !strings.Contains(s.Error, "paste it") { + if s := waitJob(t, r, "watermelon"); s.State != jobs.Failed || !strings.Contains(s.Error, "paste it") { t.Fatalf("unfetchable statement: job = %+v, want an error asking to paste it", s) } do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://usaco.org/moocast"}`, true) do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true) - if s := waitJob(t, r, "watermelon"); s.State != explain.Done { + if s := waitJob(t, r, "watermelon"); s.State != jobs.Done { t.Fatalf("job = %+v, want done", s) } if b, _ := os.ReadFile(filepath.Join(repo.dir, "solving/watermelon/problem.md")); !strings.Contains(string(b), "walkie-talkies") { diff --git a/site/internal/handlers/handlers.go b/site/internal/handlers/handlers.go index 2d266f8..c267589 100644 --- a/site/internal/handlers/handlers.go +++ b/site/internal/handlers/handlers.go @@ -21,6 +21,7 @@ import ( "regexp" "sort" "strings" + "sync" "sync/atomic" "time" @@ -29,7 +30,9 @@ import ( "adam-french.co.uk/usaco-site/internal/auth" "adam-french.co.uk/usaco-site/internal/explain" "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/jobs" "adam-french.co.uk/usaco-site/internal/repo" + "adam-french.co.uk/usaco-site/internal/usage" ) // Repo is the part of repo.Repo the handlers use, so tests can fake it. @@ -67,13 +70,20 @@ type Server struct { // RUNNER_URL is not set, which turns only running and linting off. Runner Runner + // Jobs keeps the background jobs' records (internal/jobs); nil keeps + // them in memory, which the tests use. + Jobs *jobs.Registry + // Usage is the Claude cost ledger and monthly budget; nil tracks + // nothing and allows everything. + Usage *usage.Ledger + idx atomic.Pointer[index.Index] - // Separate, so a review, an explanation and an evaluation of one - // problem can run at the same time. - jobs, reviewJobs, evalJobs explain.Jobs - // New concepts are keyed by a job id (the slug is Claude's to pick), - // rewrites by slug. - newConceptJobs, conceptJobs explain.Jobs + + jobsOnce sync.Once + // Separate kinds, so a review, an explanation and an evaluation of one + // problem can run at the same time. New concepts are keyed by a job id + // (the slug is Claude's to pick), rewrites by slug. + explainJobs, reviewJobs, evalJobs, newConceptJobs, conceptJobs *jobs.Kind } // SetIndex swaps in a freshly built index. repo.Repo calls it (through @@ -96,7 +106,10 @@ func (s *Server) Index() *index.Index { return s.idx.Load() } // Routes registers everything under api. func (s *Server) Routes(api *gin.RouterGroup) { - admin := api.Group("", auth.Require(s.Checker)) + s.initJobs() + // SameOrigin first, so a cross-site request is refused without asking + // the site backend about its cookies. + admin := api.Group("", auth.SameOrigin(), auth.Require(s.Checker)) api.GET("/health", s.health) api.GET("/me", s.me) @@ -127,6 +140,8 @@ func (s *Server) Routes(api *gin.RouterGroup) { admin.POST("/concepts/:slug/explain", s.rewriteConcept) admin.GET("/concepts/:slug/explain", s.rewriteStatus) admin.DELETE("/concepts/:slug", s.deleteConcept) + admin.POST("/jobs/:kind/:key/save", s.retrySave) + admin.GET("/usage", s.usage) api.POST("/hooks/gitea", s.webhook) } diff --git a/site/internal/handlers/handlers_test.go b/site/internal/handlers/handlers_test.go index d66158f..cdb1e91 100644 --- a/site/internal/handlers/handlers_test.go +++ b/site/internal/handlers/handlers_test.go @@ -15,6 +15,8 @@ import ( "testing" "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/repo" ) // cookieChecker: the admin is whoever sends the cookie "admin=1". @@ -31,9 +33,15 @@ type dirRepo struct { dir string srv *Server msg []string + // reject refuses that many edits, as a remote that kept moving would. + reject int } func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error { + if d.reject > 0 { + d.reject-- + return repo.ErrRejected + } if err := edit(d.dir); err != nil { return err } diff --git a/site/internal/handlers/jobs.go b/site/internal/handlers/jobs.go new file mode 100644 index 0000000..15fb56c --- /dev/null +++ b/site/internal/handlers/jobs.go @@ -0,0 +1,90 @@ +package handlers + +import ( + "errors" + "net/http" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/jobs" +) + +// saveTimeout bounds a job's commit: a sync, the edit and a push. +const saveTimeout = 2 * time.Minute + +// initJobs registers the job kinds, with the save funcs that commit their +// drafts (explain.go, review.go, concept.go). Routes calls it, and so does +// ResumeJobs, whichever runs first. +func (s *Server) initJobs() { + s.jobsOnce.Do(func() { + if s.Jobs == nil { + s.Jobs = jobs.New("") + } + s.explainJobs = s.Jobs.Kind("explain", jobs.Options{Save: s.saveExplain}) + s.reviewJobs = s.Jobs.Kind("review", jobs.Options{Save: s.saveReview, Discard: s.discardReview}) + s.evalJobs = s.Jobs.Kind("evaluate", jobs.Options{}) + s.newConceptJobs = s.Jobs.Kind("concept", jobs.Options{Save: s.saveConcept}) + s.conceptJobs = s.Jobs.Kind("rewrite", jobs.Options{Save: s.saveConcept}) + }) +} + +// ResumeJobs saves the drafts a restart interrupted. main calls it once the +// first sync has made the clone ready. +func (s *Server) ResumeJobs() { + s.initJobs() + s.Jobs.Resume() +} + +// startJob starts work as key's job of kind k, or answers why it cannot: +// busy (409) when one is running, 503 while the server shuts down. +func startJob(ctx *gin.Context, k *jobs.Kind, key, busy string, work jobs.Work) bool { + err := k.Start(key, work) + switch { + case err == nil: + return true + case errors.Is(err, jobs.ErrDraining): + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the server is restarting; try again in a minute"}) + default: + ctx.JSON(http.StatusConflict, gin.H{"error": busy}) + } + return false +} + +// claudeReady answers 503 without CLAUDE_API_KEY, and 429 once this month's +// Claude budget is spent; it is checked before any job that calls Claude. +func (s *Server) claudeReady(ctx *gin.Context) bool { + if s.Claude == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + return false + } + if err := s.Usage.Allow(time.Now()); err != nil { + ctx.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) + return false + } + return true +} + +// retrySave commits an unsaved job's draft again; the page then polls the +// job's usual status route. +func (s *Server) retrySave(ctx *gin.Context) { + k := s.Jobs.Lookup(ctx.Param("kind")) + if k == nil { + ctx.JSON(http.StatusNotFound, gin.H{"error": "no such job"}) + return + } + st, err := k.Retry(ctx.Param("key")) + switch { + case errors.Is(err, jobs.ErrBusy): + ctx.JSON(http.StatusConflict, gin.H{"error": "it is still running"}) + case err != nil: + ctx.JSON(http.StatusNotFound, gin.H{"error": "there is nothing unsaved to save"}) + default: + ctx.JSON(http.StatusAccepted, st) + } +} + +// usage is the Claude spend for the stats page. +func (s *Server) usage(ctx *gin.Context) { + ctx.JSON(http.StatusOK, s.Usage.Summarize(time.Now())) +} diff --git a/site/internal/handlers/jobs_test.go b/site/internal/handlers/jobs_test.go new file mode 100644 index 0000000..df87ca2 --- /dev/null +++ b/site/internal/handlers/jobs_test.go @@ -0,0 +1,111 @@ +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) + } +} diff --git a/site/internal/handlers/review.go b/site/internal/handlers/review.go index e841961..e2a5cb4 100644 --- a/site/internal/handlers/review.go +++ b/site/internal/handlers/review.go @@ -3,6 +3,7 @@ package handlers import ( "bytes" "context" + "encoding/json" "errors" "io" "log" @@ -62,8 +63,7 @@ func (s *Server) startReview(ctx *gin.Context) { if !ok { return } - if s.Claude == nil { - ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + if !s.claudeReady(ctx) { return } if s.Transcriber == nil { @@ -125,11 +125,9 @@ func (s *Server) startReview(ctx *gin.Context) { id := time.Now().UTC().Format(reviewIDLayout) rec := recording{name: id + ext, contentType: contentType, data: audio} link := p.URL - if !s.reviewJobs.Start(p.Name, func() error { return s.review(in, link, id, rec) }) { - ctx.JSON(http.StatusConflict, gin.H{"error": "a recording is already being reviewed"}) - return + if startJob(ctx, s.reviewJobs, p.Name, "a recording is already being reviewed", func() (any, error) { return s.review(in, link, id, rec) }) { + ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name)) } - ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name)) } func (s *Server) reviewStatus(ctx *gin.Context) { @@ -143,16 +141,26 @@ type recording struct { data []byte } -// review is one job. Its error is shown to the admin, so every path returns -// a message meant for them and logs the detail. -func (s *Server) review(in review.Input, link, id string, rec recording) (err error) { +// reviewDraft is a written review waiting to be committed. Audio is the +// recording's key in the store, kept until the review is saved or replaced. +type reviewDraft struct { + Name string `json:"name"` + ID string `json:"id"` + Fetched string `json:"fetched,omitempty"` + Markdown string `json:"markdown"` + Audio string `json:"audio,omitempty"` +} + +// review is one job's work. Its error is shown to the admin, so every path +// returns a message meant for them and logs the detail. +func (s *Server) review(in review.Input, link, id string, rec recording) (draft any, err error) { ctx, cancel := context.WithTimeout(context.Background(), reviewTimeout) defer cancel() name := in.Name fetched, err := s.ensureStatement(ctx, "review", name, &in.Statement, link) if err != nil { - return err + return nil, err } tr, err := s.Transcriber.Transcribe(ctx, rec.name, rec.data) @@ -160,17 +168,19 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er var f *transcribe.Failure if errors.As(err, &f) { log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) - return f + return nil, f } log.Printf("[review] %s: transcribing: %v", name, err) - return errors.New("the recording could not be transcribed") + return nil, errors.New("the recording could not be transcribed") } in.Transcript, in.Metrics = tr, tr.Metrics() // The recording is kept only if there is somewhere to keep it, and a // failure to keep it costs the playback, not the review. It is stored // before Claude runs so the review can point at it, and removed again - // if the review never gets saved. + // if Claude fails. Once there is a review it stays with the draft: a + // failed commit can be retried, and discardReview removes it if a new + // recording replaces the draft instead. key := "" if s.Audio != nil { k := name + "/" + rec.name @@ -194,27 +204,51 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er var f *claude.Failure if errors.As(err, &f) { log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) - return f + return nil, f } log.Printf("[review] %s: %v", name, err) - return errors.New("the review could not be written") + return nil, errors.New("the review could not be written") } + return reviewDraft{Name: name, ID: id, Fetched: fetched, Markdown: md, Audio: key}, nil +} - err = s.Repo.Mutate(ctx, "Review "+name, func(dir string) error { - status, err := findOnDisk(dir, name) +// saveReview commits a review. The id was chosen when the recording came +// in, so running it again for a draft already pushed rewrites the same +// file and commits nothing. +func (s *Server) saveReview(raw json.RawMessage) (any, error) { + var d reviewDraft + if err := json.Unmarshal(raw, &d); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), saveTimeout) + defer cancel() + err := s.Repo.Mutate(ctx, "Review "+d.Name, func(dir string) error { + status, err := findOnDisk(dir, d.Name) if err != nil { return err } - pdir := filepath.Join(dir, status, name) - if err := saveFetched(pdir, fetched); err != nil { + pdir := filepath.Join(dir, status, d.Name) + if err := saveFetched(pdir, d.Fetched); err != nil { return err } if err := os.MkdirAll(filepath.Join(pdir, "reviews"), 0o755); err != nil { return err } - return writeOrRemove(filepath.Join(pdir, "reviews", id+".md"), md) + return writeOrRemove(filepath.Join(pdir, "reviews", d.ID+".md"), d.Markdown) }) - return jobSaveError("review", name, "the review was written but could not be saved to git", err) + return nil, jobSaveError("review", d.Name, "the review was written but could not be saved to git", err) +} + +// discardReview removes the recording of a review that was never saved and +// has been replaced by a new one. +func (s *Server) discardReview(raw json.RawMessage) { + var d reviewDraft + if json.Unmarshal(raw, &d) != nil || d.Audio == "" || s.Audio == nil { + return + } + if err := s.Audio.Delete(context.Background(), d.Audio); err != nil { + log.Printf("[review] %s: removing the unsaved review's recording: %v", d.Name, err) + } } // findReview is the problem's review with the URL's id. diff --git a/site/internal/handlers/review_test.go b/site/internal/handlers/review_test.go index f1b47e7..0380739 100644 --- a/site/internal/handlers/review_test.go +++ b/site/internal/handlers/review_test.go @@ -18,8 +18,8 @@ import ( "adam-french.co.uk/usaco-site/internal/audiostore" "adam-french.co.uk/usaco-site/internal/claude" - "adam-french.co.uk/usaco-site/internal/explain" "adam-french.co.uk/usaco-site/internal/index" + "adam-french.co.uk/usaco-site/internal/jobs" "adam-french.co.uk/usaco-site/internal/review" "adam-french.co.uk/usaco-site/internal/transcribe" ) @@ -121,18 +121,18 @@ func upload(r *gin.Engine, name, filename string, size int, fields ...string) *h return do(r, "POST", "/usaco/api/problems/"+name+"/review", body.String(), true, "Content-Type", w.FormDataContentType()) } -func waitReview(t *testing.T, r *gin.Engine, name string) explain.Status { +func waitReview(t *testing.T, r *gin.Engine, name string) jobs.Status { t.Helper() for range 400 { - var s explain.Status + var s jobs.Status json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/review", "", true).Body.Bytes(), &s) - if s.State != explain.Running { + if s.State != jobs.Running { return s } time.Sleep(5 * time.Millisecond) } t.Fatal("review still running") - return explain.Status{} + return jobs.Status{} } func withStatement(t *testing.T, r *gin.Engine) { @@ -183,7 +183,7 @@ func TestReviewWritesAndCommits(t *testing.T) { if rec := upload(r, "moocast", "Take 1.M4A", 10, "note", "mock interview", "includeCode", "true"); rec.Code != 202 { t.Fatalf("start = %d: %s", rec.Code, rec.Body) } - if s := waitReview(t, r, "moocast"); s.State != explain.Done { + if s := waitReview(t, r, "moocast"); s.State != jobs.Done { t.Fatalf("job = %+v, want done", s) } if !strings.HasSuffix(ft.file, ".m4a") || string(ft.audio[:3]) != "ID3" { @@ -241,7 +241,7 @@ func TestReviewKeepsAndRemovesTheRecording(t *testing.T) { withStatement(t, r) upload(r, "moocast", "take.mp3", 100) - if s := waitReview(t, r, "moocast"); s.State != explain.Done { + if s := waitReview(t, r, "moocast"); s.State != jobs.Done { t.Fatalf("job = %+v, want done", s) } var p index.Problem @@ -288,7 +288,7 @@ func TestReviewFailures(t *testing.T) { commits := len(repo.msg) upload(r, "moocast", "a.mp3", 10) - if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "no speech was found in the recording" { + if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "no speech was found in the recording" { t.Fatalf("transcription failure: job = %+v", s) } @@ -296,7 +296,7 @@ func TestReviewFailures(t *testing.T) { // behind when the review fails. ft.err, fr.fail = nil, true upload(r, "moocast", "a.mp3", 10) - if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" { + if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" { t.Fatalf("Claude failure: job = %+v", s) } if len(repo.msg) != commits || len(store.keys()) != 0 { diff --git a/site/internal/jobs/jobs.go b/site/internal/jobs/jobs.go new file mode 100644 index 0000000..ba71b77 --- /dev/null +++ b/site/internal/jobs/jobs.go @@ -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//.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///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 + } +} diff --git a/site/internal/jobs/jobs_test.go b/site/internal/jobs/jobs_test.go new file mode 100644 index 0000000..0553dc2 --- /dev/null +++ b/site/internal/jobs/jobs_test.go @@ -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") + } +} diff --git a/site/internal/leetcode/leetcode.go b/site/internal/leetcode/leetcode.go index 87f9d87..b1d38cd 100644 --- a/site/internal/leetcode/leetcode.go +++ b/site/internal/leetcode/leetcode.go @@ -14,6 +14,7 @@ import ( "io" "net/http" "net/url" + "os" "os/exec" "path/filepath" "regexp" @@ -110,6 +111,7 @@ func (i *Importer) Import(ctx context.Context, root, slug string) error { } var stderr bytes.Buffer cmd := exec.CommandContext(ctx, python, "-I", filepath.Join(root, "lib", "leetcode.py"), root, slug) + cmd.Env = scriptEnv() cmd.Stderr = &stderr if err := cmd.Run(); err != nil { for _, line := range strings.Split(stderr.String(), "\n") { @@ -121,3 +123,22 @@ func (i *Importer) Import(ctx context.Context, root, slug string) error { } return nil } + +// scriptEnv is the environment the importer runs with: what python3 needs +// to reach LeetCode over HTTPS, and nothing else. The script comes from the +// clone, so whoever can push to the repo writes it, while this process holds +// the Claude, Gitea and S3 secrets in its environment. Those must not be +// inherited. +func scriptEnv() []string { + env := []string{"HOME=" + os.TempDir(), "LANG=C.UTF-8"} + if _, ok := os.LookupEnv("PATH"); !ok { + env = append(env, "PATH=/usr/local/bin:/usr/bin:/bin") + } + for _, k := range []string{"PATH", "TMPDIR", "SSL_CERT_FILE", "SSL_CERT_DIR", + "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"} { + if v, ok := os.LookupEnv(k); ok { + env = append(env, k+"="+v) + } + } + return env +} diff --git a/site/internal/leetcode/leetcode_test.go b/site/internal/leetcode/leetcode_test.go index db99a11..488eba6 100644 --- a/site/internal/leetcode/leetcode_test.go +++ b/site/internal/leetcode/leetcode_test.go @@ -72,3 +72,19 @@ func TestImportError(t *testing.T) { t.Fatalf("Import = %v, want the script's message", err) } } + +// The script is the clone's, so it must not see the server's secrets. +func TestImportHidesSecrets(t *testing.T) { + if _, err := exec.LookPath("python3"); err != nil { + t.Skip("no python3") + } + t.Setenv("CLAUDE_API_KEY", "sk-secret") + t.Setenv("GIT_TOKEN", "gitea-secret") + root := t.TempDir() + os.MkdirAll(filepath.Join(root, "lib"), 0o755) + script := "import os, sys\nleaked = [k for k in ('CLAUDE_API_KEY', 'GIT_TOKEN') if k in os.environ]\nprint('Error: leaked ' + ','.join(leaked) if leaked else 'Error: clean', file=sys.stderr)\nsys.exit(1)\n" + os.WriteFile(filepath.Join(root, "lib", "leetcode.py"), []byte(script), 0o644) + if err := (&Importer{}).Import(context.Background(), root, "x"); err == nil || err.Error() != "clean" { + t.Fatalf("Import = %v, want the script to see no secrets", err) + } +} diff --git a/site/internal/repo/repo.go b/site/internal/repo/repo.go index ccda65f..e64fd3b 100644 --- a/site/internal/repo/repo.go +++ b/site/internal/repo/repo.go @@ -52,10 +52,14 @@ type Repo struct { cfg Config askpass string - // onChange runs under the lock after every sync or edit, with the clone - // in a consistent state, so the index is never built from a half-reset - // tree. + // onChange runs under the lock after a sync or edit that moved HEAD, + // with the clone in a consistent state, so the index is never built + // from a half-reset tree. onChange func(dir string) error + // indexed is the HEAD onChange last succeeded on. A sync that finds + // nothing new (the interval's pull, the webhook for the site's own + // push) skips the rebuild, which reads every file and the whole log. + indexed string mu sync.Mutex } @@ -163,7 +167,16 @@ func (r *Repo) changed() error { if r.onChange == nil { return nil } - return r.onChange(r.cfg.Dir) + out, err := r.git(context.Background(), "rev-parse", "HEAD") + head := strings.TrimSpace(out) + if err == nil && head == r.indexed { + return nil + } + if err := r.onChange(r.cfg.Dir); err != nil { + return err + } + r.indexed = head + return nil } // Mutate syncs, lets edit change files in the clone, and commits the result diff --git a/site/internal/repo/repo_test.go b/site/internal/repo/repo_test.go index b63d2d7..247f811 100644 --- a/site/internal/repo/repo_test.go +++ b/site/internal/repo/repo_test.go @@ -90,6 +90,40 @@ func TestSyncClonesThenFollowsRemote(t *testing.T) { if *changes != 2 { t.Fatalf("onChange ran %d times, want 2", *changes) } + + // Nothing new: no rebuild. + if err := r.Sync(ctx); err != nil { + t.Fatal(err) + } + if *changes != 2 { + t.Fatalf("a sync with nothing new ran onChange (%d times)", *changes) + } +} + +// A rebuild that failed is tried again on the next sync, though HEAD has +// not moved since. +func TestFailedRebuildIsRetried(t *testing.T) { + bare, _ := remote(t) + fail := true + calls := 0 + r, err := New(Config{Dir: filepath.Join(t.TempDir(), "clone"), Remote: "file://" + bare, Branch: "main", Push: true}, + func(string) error { + calls++ + if fail { + return os.ErrInvalid + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if err := r.Sync(context.Background()); err == nil { + t.Fatal("the failed rebuild was not reported") + } + fail = false + if err := r.Sync(context.Background()); err != nil || calls != 2 { + t.Fatalf("retry: err %v, %d calls, want 2", err, calls) + } } func TestMutateCommitsAndPushes(t *testing.T) { diff --git a/site/internal/review/review.go b/site/internal/review/review.go index d536948..408650f 100644 --- a/site/internal/review/review.go +++ b/site/internal/review/review.go @@ -264,7 +264,7 @@ type Meta struct { // Generate asks Claude and returns the review's markdown. func Generate(ctx context.Context, a explain.Asker, in Input, meta Meta) (string, error) { var r Result - err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + err := a.JSON(ctx, claude.Request{Tag: "review", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) if err != nil { return "", err } diff --git a/site/internal/usage/usage.go b/site/internal/usage/usage.go new file mode 100644 index 0000000..3715a18 --- /dev/null +++ b/site/internal/usage/usage.go @@ -0,0 +1,234 @@ +// Package usage keeps a ledger of what the site's Claude calls cost, and +// enforces an optional monthly budget on them. +// +// Each call is one JSON line in DATA_DIR/usage.jsonl: its tokens, the model +// that answered (a server-side fallback can make that a different one) and +// an estimated cost. The estimate is the token counts times the price table +// below. It is not the bill: it leaves out the transcriber, which costs a +// fraction of a cent a minute. +package usage + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "sort" + "strings" + "sync" + "time" +) + +// Price is a model's rate in dollars per million tokens. +type Price struct{ In, Out, CacheRead float64 } + +// cacheWrite is a 5-minute cache write's rate as a multiple of the input +// rate. The site only writes 5-minute entries (claude.Client caches the +// system prompt). +const cacheWrite = 1.25 + +// prices are Anthropic's first-party rates. A model is matched by the +// longest id that prefixes it. +var prices = map[string]Price{ + "claude-fable-5-1": {10, 50, 0.25}, + "claude-fable-5": {10, 50, 1}, + "claude-opus-5-5": {4, 20, 0.20}, + "claude-opus-5": {5, 25, 0.50}, + "claude-opus-4-8": {5, 25, 0.50}, + "claude-opus-4-7": {5, 25, 0.50}, + "claude-opus-4-6": {5, 25, 0.50}, + "claude-sonnet-5-5": {2, 10, 0.20}, + "claude-sonnet-5": {2, 10, 0.20}, + "claude-sonnet-4-6": {3, 15, 0.30}, + "claude-haiku-5-5": {0.10, 0.50, 0.01}, + "claude-haiku-4-5": {1, 5, 0.10}, +} + +// unknown prices a model the table does not have at the most expensive +// rate, so a budget errs on the side of stopping early. +var unknown = prices["claude-fable-5-1"] + +// PriceOf is model's rate, and whether the table knows it. +func PriceOf(model string) (Price, bool) { + best := "" + for id := range prices { + if strings.HasPrefix(model, id) && len(id) > len(best) { + best = id + } + } + if best == "" { + return unknown, false + } + return prices[best], true +} + +// Entry is one call. +type Entry struct { + Time time.Time `json:"time"` + Kind string `json:"kind"` + Model string `json:"model"` + In int64 `json:"in"` + CacheRead int64 `json:"cacheRead,omitempty"` + CacheWrite int64 `json:"cacheWrite,omitempty"` + Out int64 `json:"out"` + Cost float64 `json:"cost"` +} + +// Estimate fills in e.Cost from its tokens. +func (e *Entry) Estimate() { + p, ok := PriceOf(e.Model) + if !ok { + log.Printf("[usage] no price for %s; counted at the highest rate", e.Model) + } + e.Cost = (float64(e.In)*p.In + float64(e.CacheRead)*p.CacheRead + + float64(e.CacheWrite)*p.In*cacheWrite + float64(e.Out)*p.Out) / 1e6 +} + +// ErrOverBudget is a call refused because this month's spend has reached +// the budget. +var ErrOverBudget = errors.New("over budget") + +// Ledger is the record of every call. A nil *Ledger records nothing and +// allows everything, so the tests and a server without a data directory +// need no special case. +type Ledger struct { + path string + budget float64 + + mu sync.Mutex + entries []Entry +} + +// Open loads the ledger at path (a missing file is an empty ledger). +// budget is the monthly limit in dollars; 0 means none. +func Open(path string, budget float64) (*Ledger, error) { + l := &Ledger{path: path, budget: budget} + f, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return l, nil + } + if err != nil { + return nil, err + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + var e Entry + if err := json.Unmarshal(sc.Bytes(), &e); err != nil { + // A line cut short by a crash costs that one call, not the + // ledger. + log.Printf("[usage] %s: skipping an unreadable line: %v", path, err) + continue + } + l.entries = append(l.entries, e) + } + return l, sc.Err() +} + +// Record estimates e's cost and appends it. +func (l *Ledger) Record(e Entry) { + if l == nil { + return + } + if e.Time.IsZero() { + e.Time = time.Now() + } + e.Estimate() + l.mu.Lock() + defer l.mu.Unlock() + l.entries = append(l.entries, e) + b, _ := json.Marshal(e) + f, err := os.OpenFile(l.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + log.Printf("[usage] %v", err) + return + } + defer f.Close() + if _, err := f.Write(append(b, '\n')); err != nil { + log.Printf("[usage] %v", err) + } +} + +func month(t time.Time) string { return t.UTC().Format("2006-01") } + +// spent is the month's total. The caller holds l.mu. +func (l *Ledger) spent(now time.Time) float64 { + m, total := month(now), 0.0 + for _, e := range l.entries { + if month(e.Time) == m { + total += e.Cost + } + } + return total +} + +// Allow refuses a new call once this month's spend has reached the budget. +// A call already running is never stopped, so a month can end a little +// over it. +func (l *Ledger) Allow(now time.Time) error { + if l == nil || l.budget <= 0 { + return nil + } + l.mu.Lock() + defer l.mu.Unlock() + if spent := l.spent(now); spent >= l.budget { + return fmt.Errorf("%w: $%.2f of this month's $%.2f Claude budget is spent; it resets on the 1st (CLAUDE_MONTHLY_BUDGET)", ErrOverBudget, spent, l.budget) + } + return nil +} + +// Total is one month's or one kind's spend. +type Total struct { + Name string `json:"name"` + Calls int `json:"calls"` + Cost float64 `json:"cost"` +} + +// Summary is what the stats page shows the admin. +type Summary struct { + Tracked bool `json:"tracked"` + Budget float64 `json:"budget,omitempty"` + Month float64 `json:"month"` + // Months are newest first; Kinds are this month's, costliest first. + Months []Total `json:"months"` + Kinds []Total `json:"kinds"` +} + +// Summarize totals the ledger by month, and this month by kind. +func (l *Ledger) Summarize(now time.Time) Summary { + s := Summary{Months: []Total{}, Kinds: []Total{}} + if l == nil { + return s + } + l.mu.Lock() + defer l.mu.Unlock() + s.Tracked, s.Budget, s.Month = true, l.budget, l.spent(now) + months, kinds := map[string]*Total{}, map[string]*Total{} + add := func(m map[string]*Total, name string, e Entry) { + t := m[name] + if t == nil { + t = &Total{Name: name} + m[name] = t + } + t.Calls++ + t.Cost += e.Cost + } + this := month(now) + for _, e := range l.entries { + add(months, month(e.Time), e) + if month(e.Time) == this { + add(kinds, e.Kind, e) + } + } + for _, t := range months { + s.Months = append(s.Months, *t) + } + for _, t := range kinds { + s.Kinds = append(s.Kinds, *t) + } + sort.Slice(s.Months, func(i, j int) bool { return s.Months[i].Name > s.Months[j].Name }) + sort.Slice(s.Kinds, func(i, j int) bool { return s.Kinds[i].Cost > s.Kinds[j].Cost }) + return s +} diff --git a/site/internal/usage/usage_test.go b/site/internal/usage/usage_test.go new file mode 100644 index 0000000..7565f1c --- /dev/null +++ b/site/internal/usage/usage_test.go @@ -0,0 +1,72 @@ +package usage + +import ( + "errors" + "math" + "os" + "path/filepath" + "testing" + "time" +) + +func near(a, b float64) bool { return math.Abs(a-b) < 1e-9 } + +func TestEstimate(t *testing.T) { + e := Entry{Model: "claude-opus-5-5", In: 1_000_000, CacheRead: 1_000_000, CacheWrite: 1_000_000, Out: 1_000_000} + e.Estimate() + if want := 4 + 0.20 + 5 + 20.0; !near(e.Cost, want) { + t.Fatalf("opus 5.5 = %v, want %v", e.Cost, want) + } + // The longest prefix wins: claude-opus-5-5 is not claude-opus-5. + if p, ok := PriceOf("claude-opus-5"); !ok || p.In != 5 { + t.Fatalf("opus 5 = %+v %v", p, ok) + } + if p, ok := PriceOf("claude-something-new"); ok || p != unknown { + t.Fatalf("unknown = %+v %v", p, ok) + } +} + +func TestBudgetAndSummary(t *testing.T) { + path := filepath.Join(t.TempDir(), "usage.jsonl") + l, err := Open(path, 1) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 10, 23, 12, 0, 0, 0, time.UTC) + last := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC) + // $0.40 output each on Opus 5.5. + l.Record(Entry{Time: last, Kind: "explain", Model: "claude-opus-5-5", Out: 20_000}) + l.Record(Entry{Time: now, Kind: "explain", Model: "claude-opus-5-5", Out: 20_000}) + if err := l.Allow(now); err != nil { + t.Fatalf("$0.40 of $1 refused: %v", err) + } + l.Record(Entry{Time: now, Kind: "review", Model: "claude-opus-5-5", Out: 40_000}) + if err := l.Allow(now); !errors.Is(err, ErrOverBudget) { + t.Fatalf("$1.20 of $1 = %v", err) + } + + // Reopened from disk, with a torn last line. + f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) + f.WriteString(`{"time":"2026-10`) + f.Close() + l, err = Open(path, 0) + if err != nil { + t.Fatal(err) + } + if err := l.Allow(now); err != nil { + t.Fatalf("no budget refused: %v", err) + } + s := l.Summarize(now) + if !s.Tracked || !near(s.Month, 1.2) || len(s.Months) != 2 || s.Months[0].Name != "2026-10" || s.Months[0].Calls != 2 { + t.Fatalf("summary = %+v", s) + } + if len(s.Kinds) != 2 || s.Kinds[0].Name != "review" { + t.Fatalf("kinds = %+v", s.Kinds) + } + + var none *Ledger + none.Record(Entry{Model: "claude-opus-5-5"}) + if none.Allow(now) != nil || none.Summarize(now).Tracked { + t.Fatal("a nil ledger should allow everything and track nothing") + } +} diff --git a/site/web/src/App.vue b/site/web/src/App.vue index 1cac0c0..2707820 100644 --- a/site/web/src/App.vue +++ b/site/web/src/App.vue @@ -20,7 +20,6 @@ const route = useRoute(); Concepts Stats CLI - Source adam-french.co.uk diff --git a/site/web/src/api.js b/site/web/src/api.js index 9630535..77ae1bc 100644 --- a/site/web/src/api.js +++ b/site/web/src/api.js @@ -83,3 +83,13 @@ export const conceptJob = (id) => request("GET", `/concept-jobs/${encodeURICompo export const rewriteConcept = (slug, body) => request("POST", `/concepts/${encodeURIComponent(slug)}/explain`, body); export const rewriteStatus = (slug) => request("GET", `/concepts/${encodeURIComponent(slug)}/explain`); export const deleteConcept = (slug) => request("DELETE", `/concepts/${encodeURIComponent(slug)}`); + +// Every job status carries its kind and key. One that ends with unsaved: +// true wrote its answer but could not commit it; this commits that answer +// again, without asking Claude again, and answers the job (running), which +// is then polled at its usual status route. +export const saveJobAgain = (job) => + request("POST", `/jobs/${encodeURIComponent(job.kind)}/${encodeURIComponent(job.key)}/save`); + +// The admin's Claude spend: { tracked, budget, month, months, kinds }. +export const getUsage = () => request("GET", "/usage"); diff --git a/site/web/src/views/CliPage.vue b/site/web/src/views/CliPage.vue index b27e1cb..2e5b1f4 100644 --- a/site/web/src/views/CliPage.vue +++ b/site/web/src/views/CliPage.vue @@ -2,13 +2,23 @@ /** * How to use ./usaco, the workspace CLI. A condensed copy of the repo * README's Commands section: the Docker build context is site/, so the README - * itself can't be imported. Keep the two in step when the CLI changes. + * itself can't be imported. Keep the two in step when the CLI changes; + * site/docs_test.go fails when a command in the README is missing here. */ +import { ref } from "vue"; +import { getMe } from "@/api"; + // The repo on the site's Gitea, behind the same nginx, so a root-relative -// link works. +// link works. It is private (it holds the judges' statements and the +// admin's review transcripts), so only the admin gets links into it; for +// anyone else they would be 404s, and the names render as plain text. const repo = "/gitea/adamf/usaco"; -const src = (path) => `${repo}/src/branch/main/${path}`; +const admin = ref(false); +getMe() + .then((me) => (admin.value = me.admin)) + .catch(() => {}); +const src = (path) => (admin.value ? (path ? `${repo}/src/branch/main/${path}` : repo) : undefined); // Every command that takes a problem name accepts a unique prefix, so the // examples use the full name only where it reads better. @@ -91,7 +101,7 @@ usaco [watermelon:solved]> q`;

The usaco CLI

Every problem here is written in a workspace managed by ./usaco, a small bash script at - the root of the repo on Gitea (the commands themselves are in + the root of the repo on Gitea (the commands themselves are in lib/cmd/). Each problem lives in solving/, solved/ or skipped/ as a directory with main.cpp or main.rs and its .in/.out files. Wherever a command takes a problem name, a unique prefix works too: @@ -102,8 +112,11 @@ usaco [watermelon:solved]> q`;

Setup

-

Clone the repo and run ./usaco from its root:

-
git clone https://www.adam-french.co.uk{{ repo }}.git
+ +

The repo is private. In a clone of it, run ./usaco from its root.

Or add this to ~/.zshrc:

source ~/Coding/USACO/usaco.zsh

diff --git a/site/web/src/views/ConceptList.vue b/site/web/src/views/ConceptList.vue index 1484910..3288562 100644 --- a/site/web/src/views/ConceptList.vue +++ b/site/web/src/views/ConceptList.vue @@ -11,7 +11,7 @@ */ import { computed, onMounted, onUnmounted, ref } from "vue"; import { RouterLink, useRoute, useRouter } from "vue-router"; -import { conceptJob, listConcepts, startConcept } from "@/api"; +import { conceptJob, listConcepts, saveJobAgain, startConcept } from "@/api"; import { formatDate } from "@/format"; const route = useRoute(); @@ -84,6 +84,17 @@ async function ask() { } } +// Written but not committed: commit the same answer again. +async function saveAgain() { + try { + job.value = await saveJobAgain(job.value); + remember(job.value.key); + poll = setTimeout(() => check(job.value.key), 3000); + } catch (e) { + job.value = { state: "error", error: e.message }; + } +} + const canAsk = computed( () => job.value.state !== "running" && (topic.value.trim() || (showCode.value && code.value.trim())), ); @@ -147,7 +158,10 @@ onUnmounted(() => clearTimeout(poll)); This takes a minute or two; the concept opens when it is saved.

-

{{ job.error }}

+

+ {{ job.error }} + +

diff --git a/site/web/src/views/ConceptPage.vue b/site/web/src/views/ConceptPage.vue index 2b97b64..229055c 100644 --- a/site/web/src/views/ConceptPage.vue +++ b/site/web/src/views/ConceptPage.vue @@ -7,7 +7,7 @@ */ import { onUnmounted, ref, watch } from "vue"; import { RouterLink, useRouter } from "vue-router"; -import { deleteConcept, getConcept, getMe, rewriteConcept, rewriteStatus } from "@/api"; +import { deleteConcept, getConcept, getMe, rewriteConcept, rewriteStatus, saveJobAgain } from "@/api"; import { formatDate } from "@/format"; import CodeBlock from "@/components/CodeBlock.vue"; import Explanation from "@/components/Explanation.vue"; @@ -81,6 +81,15 @@ async function rewrite() { } } +async function saveAgain() { + try { + job.value = await saveJobAgain(job.value); + poll = setTimeout(checkRewrite, 3000); + } catch (e) { + job.value = { state: "error", error: e.message }; + } +} + async function forget() { if (!confirm(`Delete “${concept.value.title}” and its snippet?`)) return; actionError.value = ""; @@ -130,7 +139,10 @@ async function forget() {
-

Rewrite: {{ job.error }}

+

+ Rewrite: {{ job.error }} + +

{{ actionError }}

diff --git a/site/web/src/views/ProblemPage.vue b/site/web/src/views/ProblemPage.vue index be07b23..6248717 100644 --- a/site/web/src/views/ProblemPage.vue +++ b/site/web/src/views/ProblemPage.vue @@ -21,6 +21,7 @@ import { getMe, getProblem, reviewStatus, + saveJobAgain, setStatus, startExplain, startReview, @@ -186,6 +187,16 @@ async function explain() { } } +// The explanation was written but not committed: commit it again. +async function saveExplainAgain() { + try { + job.value = await saveJobAgain(job.value); + poll = setTimeout(checkExplain, 3000); + } catch (e) { + job.value = { state: "error", error: e.message }; + } +} + const canExplain = computed(() => !!(problem.value?.statement || problem.value?.url)); // ---- recording reviews ---- @@ -258,6 +269,15 @@ async function checkReview() { } } +async function saveReviewAgain() { + try { + reviewJob.value = await saveJobAgain(reviewJob.value); + reviewPoll = setTimeout(checkReview, 3000); + } catch (e) { + reviewJob.value = { state: "error", error: e.message }; + } +} + async function submitReview() { const form = new FormData(); form.append("audio", recording.value); @@ -409,8 +429,14 @@ const moves = computed(() => {

{{ editError }}

-

Explain: {{ job.error }}

-

Review: {{ reviewJob.error }}

+

+ Explain: {{ job.error }} + +

+

+ Review: {{ reviewJob.error }} + +

diff --git a/site/web/src/views/StatsPage.vue b/site/web/src/views/StatsPage.vue index e4e4092..03cbb87 100644 --- a/site/web/src/views/StatsPage.vue +++ b/site/web/src/views/StatsPage.vue @@ -4,13 +4,15 @@ * headline counts, a year of solves as a calendar heatmap, and the same data * by month as a table (the heatmap's accessible equivalent). * + * The admin also sees what Claude has cost (GET /usage, the server's ledger). + * * Days are the viewer's local days (format.dayKey). The solve date is the * commit that moved a problem into solved/, so a batch of problems committed * together lands on one day. */ import { computed, nextTick, onMounted, ref } from "vue"; import { RouterLink } from "vue-router"; -import { listProblems } from "@/api"; +import { getMe, getUsage, listProblems } from "@/api"; import { dayKey, formatDate, title } from "@/format"; const problems = ref([]); @@ -18,7 +20,16 @@ const loading = ref(true); const error = ref(""); const scroller = ref(null); +// The Claude spend; null for anyone but the admin. +const spend = ref(null); +const money = (n) => `$${n.toFixed(2)}`; +const KIND_LABELS = { explain: "Explanations", concept: "Concepts", review: "Reviews", evaluate: "Evaluations" }; + onMounted(async () => { + getMe() + .then((me) => (me.admin ? getUsage() : null)) + .then((u) => (spend.value = u?.tracked ? u : null)) + .catch(() => {}); try { problems.value = (await listProblems()).problems; } catch (e) { @@ -224,6 +235,38 @@ const monthly = computed(() => {

Nothing solved yet.

+ +
+

Claude spend

+

+ {{ money(spend.month) }} this month. + Estimated from token counts at list prices; transcription is not included. +

+ + + + + + + + + + + +
MonthCallsCost
{{ formatDate(m.name + "-01T00:00:00", { month: "long", year: "numeric" }) }}{{ m.calls }}{{ money(m.cost) }}
+ + + + + + + + + + + +
This month, by featureCallsCost
{{ KIND_LABELS[k.name] || k.name }}{{ k.calls }}{{ money(k.cost) }}
+
@@ -259,6 +302,9 @@ const monthly = computed(() => { .stats > section { min-width: 0; } +table + table { + margin-top: 12px; +} h2 { font-size: 1.6rem; margin-bottom: 8px;