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,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
|
||||
}
|
||||
Reference in New Issue
Block a user