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