package handlers import ( "context" "encoding/json" "errors" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" "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/repo" "adam-french.co.uk/usaco-site/internal/statement" ) // Fetcher is the part of statement.Fetcher the handlers use, so tests can // fake the judges. type Fetcher interface { Fetch(ctx context.Context, link string) (string, error) } func (s *Server) fetcher() Fetcher { if s.Statements != nil { return s.Statements } return &statement.Fetcher{} } // fetchStatement returns the statement behind ?url= (or the saved link) for // the admin to review in the editor. It saves nothing. func (s *Server) fetchStatement(ctx *gin.Context) { p, ok := s.lookup(ctx, true) if !ok { return } link := strings.TrimSpace(ctx.Query("url")) if link == "" { link = p.URL } if u, err := url.Parse(link); link == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") { ctx.JSON(http.StatusBadRequest, gin.H{"error": "give the problem an http(s) link first"}) return } c, cancel := context.WithTimeout(ctx.Request.Context(), 20*time.Second) defer cancel() md, err := s.fetcher().Fetch(c, link) switch { case errors.Is(err, statement.ErrUnsupported): ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) case err != nil: log.Printf("[statement] %s: %v", link, err) ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()}) default: ctx.JSON(http.StatusOK, gin.H{"statement": md}) } } type explainBody struct { Note string `json:"note"` IncludeCode bool `json:"includeCode"` } const maxNote = 4 << 10 // Claude can take a few minutes at high effort; this also bounds the // commit that follows. const explainTimeout = 10 * time.Minute // startExplain starts writing explain.md and answers at once; the page polls // explainStatus. Everything Claude sees is taken from the index now, so a // sync during the call changes nothing but where the result is committed. func (s *Server) startExplain(ctx *gin.Context) { p, ok := s.lookup(ctx, true) if !ok { return } if !s.claudeReady(ctx) { return } var body explainBody 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 } if strings.TrimSpace(p.Statement) == "" && p.URL == "" { ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"}) return } in := explain.Input{Name: p.Name, Statement: p.Statement, Note: body.Note, Examples: examples(p)} if body.IncludeCode { in.Code = mainFile(p) } link := p.URL 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)) } } func (s *Server) explainStatus(ctx *gin.Context) { if p, ok := s.lookup(ctx, true); ok { ctx.JSON(http.StatusOK, s.explainJobs.Get(p.Name)) } } // 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 nil, err } md, err := explain.Generate(ctx, s.Claude, in, time.Now()) if err != nil { var f *claude.Failure if errors.As(err, &f) { log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err) return nil, f } log.Printf("[explain] %s: %v", in.Name, err) return nil, errors.New("the explanation could not be written") } return explainDraft{Name: in.Name, Fetched: fetched, Markdown: md}, nil } // 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, d.Name) if err := saveFetched(pdir, d.Fetched); err != nil { return err } return writeOrRemove(filepath.Join(pdir, "explain.md"), d.Markdown) }) 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 // run on a problem that only has a link. It returns what it fetched, for // saveFetched to keep alongside the job's result so the next job does not // need the judge. tag is the log prefix. func (s *Server) ensureStatement(ctx context.Context, tag, name string, statement *string, link string) (string, error) { if strings.TrimSpace(*statement) != "" { return "", nil } md, err := s.fetcher().Fetch(ctx, link) if err != nil { log.Printf("[%s] %s: fetching %s: %v", tag, name, link, err) return "", fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err) } *statement = md return md, nil } // saveFetched writes a statement ensureStatement fetched, but only if it is // still missing: the admin may have pasted one while Claude was working. func saveFetched(pdir, fetched string) error { if fetched == "" { return nil } if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) { return writeOrRemove(filepath.Join(pdir, "problem.md"), fetched) } return nil } // jobSaveError turns a job's Mutate error into a message for the admin. func jobSaveError(tag, name, unsaved string, err error) error { var re *requestError switch { case err == nil: return nil case errors.As(err, &re): return errors.New(re.msg) case errors.Is(err, repo.ErrRejected): return errors.New("the repository changed while saving; try again") default: log.Printf("[%s] %s: saving: %v", tag, name, err) return errors.New(unsaved) } } // mainFile is the CLI's solution (main.cpp, main.rs...), else the first // solution file. func mainFile(p *index.Problem) *index.File { for i := range p.Files { if strings.HasPrefix(p.Files[i].Name, "main.") { return &p.Files[i] } } if len(p.Files) > 0 { return &p.Files[0] } return nil } // A case bigger than this is a stress test, not something to trace by hand, // and a truncated one would mislead. const maxExample = 2 << 10 // examples are the saved tests that have an expected output, then the // sample input if no test has the same input. Three is plenty to trace. func examples(p *index.Problem) []explain.Example { var out []explain.Example seen := map[string]bool{} for _, t := range p.TestSet { if len(out) == 3 { return out } if t.Output == nil || t.Input.Truncated || len(t.Input.Content) > maxExample || len(t.Output.Content) > maxExample { continue } out = append(out, explain.Example{In: t.Input.Content, Out: t.Output.Content}) seen[strings.TrimSpace(t.Input.Content)] = true } if sm := p.Sample; sm != nil && len(out) < 3 && len(sm.Content) <= maxExample && !seen[strings.TrimSpace(sm.Content)] { out = append(out, explain.Example{In: sm.Content}) } return out }