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

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

136 lines
4.5 KiB
Go

package claude
import (
"context"
"encoding/json"
"errors"
"fmt"
"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.
func sse(text, stop string) string {
ev := func(typ string, data any) string {
b, _ := json.Marshal(data)
return fmt.Sprintf("event: %s\ndata: %s\n\n", typ, b)
}
return ev("message_start", map[string]any{"type": "message_start", "message": map[string]any{
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-5-5", "content": []any{},
"usage": map[string]any{"input_tokens": 10, "output_tokens": 0}}}) +
ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}) +
ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": text}}) +
ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) +
ev("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop}, "usage": map[string]any{"output_tokens": 5}}) +
ev("message_stop", map[string]any{"type": "message_stop"})
}
func fake(t *testing.T, status int, reply string, got *map[string]any, header *http.Header) *Client {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if got != nil {
json.Unmarshal(b, got)
}
if header != nil {
*header = r.Header.Clone()
}
if status != 200 {
w.WriteHeader(status)
w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`))
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Write([]byte(reply))
}))
t.Cleanup(srv.Close)
c, err := New("k", "", option.WithBaseURL(srv.URL), option.WithMaxRetries(0))
if err != nil {
t.Fatal(err)
}
return c
}
func TestNotConfigured(t *testing.T) {
if _, err := New("", ""); !errors.Is(err, ErrNotConfigured) {
t.Fatalf("blank key: %v", err)
}
}
func TestJSONRequestAndReply(t *testing.T) {
var body map[string]any
var hdr http.Header
c := fake(t, 200, sse(`{"a":"hi"}`, "end_turn"), &body, &hdr)
var out struct{ A string }
err := c.JSON(context.Background(), Request{System: "sys", User: "u", Schema: map[string]any{"type": "object"}, MaxTokens: 100}, &out)
if err != nil {
t.Fatal(err)
}
if out.A != "hi" {
t.Errorf("decoded %+v", out)
}
if body["model"] != DefaultModel || body["stream"] != true || body["fallbacks"] != "default" {
t.Errorf("model/stream/fallbacks = %v %v %v", body["model"], body["stream"], body["fallbacks"])
}
oc, _ := body["output_config"].(map[string]any)
format, _ := oc["format"].(map[string]any)
if oc["effort"] != "high" || format["type"] != "json_schema" || format["schema"] == nil {
t.Errorf("output_config = %v", oc)
}
if !strings.Contains(hdr.Get("Anthropic-Beta"), "server-side-fallback-2026-07-01") {
t.Errorf("beta header = %q", hdr.Get("Anthropic-Beta"))
}
}
func TestFailures(t *testing.T) {
cases := []struct {
name string
status int
reply string
want string
}{
{"refusal", 200, sse("", "refusal"), "declined"},
{"cut off", 200, sse(`{"a":`, "max_tokens"), "length limit"},
{"not json", 200, sse("plain words", "end_turn"), "could not be read"},
{"bad key", 401, "", "key was refused"},
{"overloaded", 529, "", "unavailable"},
}
for _, tc := range cases {
c := fake(t, tc.status, tc.reply, nil, nil)
var out map[string]any
err := c.JSON(context.Background(), Request{System: "s", User: "u", Schema: map[string]any{}, MaxTokens: 10}, &out)
var f *Failure
if !errors.As(err, &f) || !strings.Contains(f.Msg, tc.want) {
t.Errorf("%s: err = %v, want a Failure mentioning %q", tc.name, err, tc.want)
}
}
}
// 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)
}
}