Files
usaco/site/internal/handlers/concept.go
T
adamfandClaude Opus 5.5 cae5ec8e5a
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s
Keep site jobs across restarts, meter Claude spend, harden admin routes
- internal/jobs replaces explain.Jobs: one registry for every kind of
  background job, with records in DATA_DIR/jobs. A job's draft is written
  before its commit, so a failed commit can be saved again (POST
  /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without
  paying Claude twice.
- Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for
  running ones while still serving the pages that poll them.
- internal/usage records every Claude call's tokens and estimated cost in
  DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a
  month reaches it. The stats page shows the admin the spend.
- auth.SameOrigin refuses cross-origin writes to admin routes.
- The LeetCode importer runs the clone's script without the server's
  secrets in its environment.
- A sync that leaves HEAD where it was skips the re-index.
- docs_test.go checks README's route table against the routes, and the CLI
  page against the root README's commands.
- The repo is going private: Gitea links on the site are admin-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:10:01 +01:00

298 lines
9.3 KiB
Go

package handlers
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/concept"
"adam-french.co.uk/usaco-site/internal/index"
)
// listConcepts is the library, newest first. It leaves out the content and
// snippets, which only a concept's own page needs.
func (s *Server) listConcepts(ctx *gin.Context) {
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
return
}
out := []index.Concept{}
for _, c := range idx.Concepts {
sum := *c
sum.Content, sum.Snippet = "", nil
out = append(out, sum)
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i].Updated, out[j].Updated
if (a == nil) != (b == nil) {
return a == nil // uncommitted ones are the newest
}
if a != nil && !a.Equal(*b) {
return a.After(*b)
}
return out[i].Slug < out[j].Slug
})
ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx), "concepts": out})
}
func (s *Server) lookupConcept(ctx *gin.Context) (*index.Concept, bool) {
slug := ctx.Param("slug")
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
return nil, false
}
c, ok := idx.Concepts[slug]
if !validName.MatchString(slug) || !ok {
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such concept"})
return nil, false
}
return c, true
}
func (s *Server) getConcept(ctx *gin.Context) {
if c, ok := s.lookupConcept(ctx); ok {
ctx.JSON(http.StatusOK, c)
}
}
type conceptBody struct {
Topic string `json:"topic"`
Code string `json:"code"`
}
const maxConceptCode = 32 << 10
// startConcept starts explaining a new concept. Its slug is Claude's to
// 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.claudeReady(ctx) {
return
}
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
return
}
var body conceptBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
switch {
case strings.TrimSpace(body.Topic) == "" && strings.TrimSpace(body.Code) == "":
ctx.JSON(http.StatusBadRequest, gin.H{"error": "say what to explain"})
return
case len(body.Topic) > maxNote:
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the topic is too long"})
return
case len(body.Code) > maxConceptCode:
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the code is too long"})
return
}
topic := strings.TrimSpace(body.Topic)
if topic == "" {
topic = "How does this code work?"
}
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 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)})
}
}
func (s *Server) newConceptStatus(ctx *gin.Context) {
ctx.JSON(http.StatusOK, s.newConceptJobs.Get(ctx.Param("id")))
}
type rewriteBody struct {
Note string `json:"note"`
}
// rewriteConcept explains a saved concept again, from the question it was
// asked with, the current version and what the admin wants changed.
func (s *Server) rewriteConcept(ctx *gin.Context) {
c, ok := s.lookupConcept(ctx)
if !ok {
return
}
if !s.claudeReady(ctx) {
return
}
var body rewriteBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
topic, code := concept.ParseRequest(c.Request)
if topic == "" {
topic = c.Title
}
prev := "# " + c.Title + "\n\n" + c.Content
if c.Snippet != nil {
prev += "\n\n## Snippet\n\n```cpp\n" + c.Snippet.Content + "\n```"
}
in := concept.Input{Topic: topic, Code: code, Previous: prev, Note: body.Note, Existing: conceptRefs(s.Index(), c.Slug)}
slug := c.Slug
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))
}
}
func (s *Server) rewriteStatus(ctx *gin.Context) {
if c, ok := s.lookupConcept(ctx); ok {
ctx.JSON(http.StatusOK, s.conceptJobs.Get(c.Slug))
}
}
// conceptRefs are the saved concepts but skip, for Claude to name a new one
// apart from.
func conceptRefs(idx *index.Index, skip string) []concept.Ref {
var refs []concept.Ref
for _, c := range idx.Concepts {
if c.Slug != skip {
refs = append(refs, concept.Ref{Slug: c.Slug, Title: c.Title})
}
}
sort.Slice(refs, func(i, j int) bool { return refs[i].Slug < refs[j].Slug })
return refs
}
// conceptResult is a finished job's answer: where the concept is now.
type conceptResult struct {
Slug string `json:"slug"`
}
// 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()
r, err := concept.Generate(ctx, s.Claude, in)
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[concept] %s: %s: %v", in.Topic, f.Msg, f.Err)
return nil, f
}
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
}
// 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
}
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; 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
}
for name, content := range files {
if err := writeOrRemove(filepath.Join(cdir, name), content); err != nil {
return err
}
}
return nil
})
if err := jobSaveError("concept", slug, "the explanation was written but could not be saved to git", err); err != nil {
return nil, err
}
return conceptResult{Slug: slug}, nil
}
// 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++ {
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)
}
}
func (s *Server) deleteConcept(ctx *gin.Context) {
c, ok := s.lookupConcept(ctx)
if !ok {
return
}
slug := c.Slug
cctx, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
msg := "Forget concept " + slug
err := s.Repo.Mutate(cctx, msg, func(dir string) error {
// Already gone on a newer tip is what was asked for.
return os.RemoveAll(filepath.Join(dir, index.Concepts, slug))
})
if err != nil {
editFailed(ctx, msg, err)
return
}
ctx.JSON(http.StatusOK, gin.H{})
}