Keep site jobs across restarts, meter Claude spend, harden admin routes
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:10:01 +01:00
co-authored by Claude Opus 5.5
parent 7638d88570
commit cae5ec8e5a
42 changed files with 1849 additions and 264 deletions
+28
View File
@@ -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}
+22
View File
@@ -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)
}
}