Files
magpie/internal/gateway/key_limit_test.go
T
yetone 0879894af3 gateway: each gateway key can have its own limit, a token total and/or an estimated cost per day, week or month, and a spent key is refused before any provider is asked (margbug01 on #585, v0.1.671: 每个网关密钥都能设置自己的用量上限) — a gateway key named who called and the Usage page grouped its calls, but nothing held a key to an amount, so one client shared on the network could spend a subscription's whole window. A key now carries limit {period day|week|month, tokens, cost, cacheReads} in caller-keys.json, set with the new "limit-key" change. Windows are calendar ones in local time (from midnight, from Monday, from the 1st) and a call counts in the window it started in. Tokens are a call's uncached input, output and cache writes, plus cache reads when the limit says so; cost is an estimate at the Usage page's effective prices (usage.NewCoster), a call with no known price adding none and counted as unpriced. What a key used is summed from usage.jsonl (usage.Visit), so it survives a restart; the new internal/budget keeps the sums in memory per window and appendUsage writes a key's record through budget.Append, which appends and counts under one lock so a window read meanwhile never counts a call twice. Before a keyed POST reaches the mux, keyLimited reserves for it: its body's size in tokens (4 bytes a token) plus the key's mean output per call this window, at the window's cost per token or the named model's input price; it is let in while used + reserved is under the cap, so requests sent at once overshoot by about one call, and the reservation is released when the request ends, a streamed reply being settled then with the usage its vendor reported. A spent key gets a 429 in its API's error shape (Anthropic, OpenAI chat/responses, Gemini) naming the key, the cap and the reset time, with Retry-After, X-Should-Retry: false and X-Magpie-Limit-Reset, recorded as a rejected call (gateway_key_limit); other keys go on. Requests from this computer without a gateway key are not limited; a key used from this computer is. count_tokens and bridge callbacks are never held. GET /v1/magpie/limit tells a key its own status. Gateway keys rows show a Limit badge (what is used of it, per what, Spent in red) and a line under a limited key (used of limit, left, resets / refused until, in flight; unpriced calls in its title); Limit opens an editor under the row (window, tokens with k/m/万/亿, cost in US$, Count cache reads too, what is counted) staged until Save, marked unsaved, Cancel/Escape dropping it, a bad amount disabling Save, No limit removing it; en and zh; no left-border accent; no click scrolls. The CLI gains magpie gateway-key limit <id> [off | day|week|month --tokens N --cost USD --cache-reads] and a LIMIT column in list. TestKeyLimitRefusesBeforeUpstream (two calls within 700 tokens, the third a 429 the fake upstream never sees, message/type/headers, the rejected record, Anthropic's shape on /v1/messages, another key and a keyless loopback request let in, still refused after budget.Forget as after a restart, a raised and a removed limit let in, /v1/magpie/limit), TestKeyLimitHoldsParallelRequests (20 at once against 2000 tokens: some refused, at most one call over, no reservation left; without the reservation all 20 got in and 7350 were used), TestKeyLimitWindowResets, TestLimitWindow, TestLimitValid and TestGatewayKeyLimitCLI are new; gateway-key-limit.test.cjs (WebKit, en and zh) is new and passes, as do gateway-caller-keys, gateway-connect-keys, api-key-theme and click-scroll (whose request-pick case flaked once under a parallel run and passes alone, as on main). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState's known TempDir-cleanup flake aside).
2026-10-03 00:18:16 +08:00

229 lines
7.9 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// limitedUpstream is a provider whose every call uses 300 input and 50
// output tokens, counting the calls it is sent.
func limitedUpstream(t *testing.T, delay time.Duration) *atomic.Int64 {
t.Helper()
var calls atomic.Int64
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
time.Sleep(delay)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":300,"completion_tokens":50}}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
return &calls
}
func setLimit(t *testing.T, id string, l *access.Limit) {
t.Helper()
if _, err := access.Update("limit-key", access.Change{Key: id, Limit: l}); err != nil {
t.Fatal(err)
}
}
// A key past its limit is refused before any provider is asked, with a
// 429 that names the key, the limit and when it resets; another key and a
// keyless request from this computer go on; what was used survives a
// restart; raising the limit lets it in again (#585).
func TestKeyLimitRefusesBeforeUpstream(t *testing.T) {
fresh(t)
budget.Forget()
calls := limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Capped", "Other")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
h := New().Handler()
call := func(secret, path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
} else {
r.RemoteAddr = "127.0.0.1:5000"
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
for i := range 2 {
if w := call(secrets[0], "/v1/chat/completions", chatReq); w.Code != 200 {
t.Fatal("within the limit", i, w.Code, w.Body.String())
}
}
if calls.Load() != 2 {
t.Fatal(calls.Load())
}
w := call(secrets[0], "/v1/chat/completions", chatReq)
if w.Code != http.StatusTooManyRequests {
t.Fatal("spent key let in", w.Code, w.Body.String())
}
if calls.Load() != 2 {
t.Fatal("a spent key's request reached the provider")
}
var e struct {
Error struct{ Message, Type string }
}
json.Unmarshal(w.Body.Bytes(), &e)
if e.Error.Type != "rate_limit_error" || !strings.Contains(e.Error.Message, `"Capped"`) || !strings.Contains(e.Error.Message, "700 of its 700") || !strings.Contains(e.Error.Message, "resets at") {
t.Fatal("refusal says", w.Body.String())
}
if ra, _ := strconv.Atoi(w.Header().Get("Retry-After")); ra <= 0 || ra > 86400+3600 || w.Header().Get("X-Should-Retry") != "false" {
t.Fatal("headers", w.Header())
}
rec := lastUsage(t)
if !rec.Rejected || rec.CallerKeyID != keys[0].ID || rec.ErrType != "gateway_key_limit" || rec.Status != 429 {
t.Fatalf("refusal recorded as %+v", rec)
}
// said in Anthropic's shape on its API
w = call(secrets[0], "/v1/messages", `{"model":"plan/m1","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)
var a struct {
Type string
Error struct{ Type string }
}
json.Unmarshal(w.Body.Bytes(), &a)
if w.Code != 429 || a.Type != "error" || a.Error.Type != "rate_limit_error" || calls.Load() != 2 {
t.Fatal("anthropic refusal", w.Code, w.Body.String())
}
if w := call(secrets[1], "/v1/chat/completions", chatReq); w.Code != 200 {
t.Fatal("another key held to the spent one's limit", w.Code)
}
if w := call("", "/v1/chat/completions", chatReq); w.Code != 200 {
t.Fatal("a keyless loopback request was limited", w.Code)
}
// the gateway restarts: the window is read back from usage.jsonl
budget.Forget()
if w := call(secrets[0], "/v1/chat/completions", chatReq); w.Code != 429 {
t.Fatal("a restart forgot what the key used", w.Code)
}
st := budget.Of(access.Key{ID: keys[0].ID, Limit: &access.Limit{Period: "day", Tokens: 700}}, time.Now())
if st == nil || st.Tokens != 700 || st.Calls != 2 || !st.Spent || st.TokensLeft != 0 {
t.Fatalf("status %+v", st)
}
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 1050})
if w := call(secrets[0], "/v1/chat/completions", chatReq); w.Code != 200 {
t.Fatal("a raised limit still refused", w.Code)
}
setLimit(t, keys[0].ID, nil)
if w := call(secrets[0], "/v1/chat/completions", chatReq); w.Code != 200 {
t.Fatal("no limit still refused", w.Code)
}
// the key asks after its own limit
setLimit(t, keys[0].ID, &access.Limit{Period: "week", Tokens: 5000})
r := httptest.NewRequest("GET", "/v1/magpie/limit", nil)
r.Header.Set("Authorization", "Bearer "+secrets[0])
lw := httptest.NewRecorder()
h.ServeHTTP(lw, r)
var got struct {
Limited bool
Limit budget.Status
}
json.Unmarshal(lw.Body.Bytes(), &got)
if !got.Limited || got.Limit.Tokens != 1400 || got.Limit.TokensLeft != 3600 || got.Limit.Period != "week" {
t.Fatal("limit endpoint", lw.Body.String())
}
}
// N requests at once can't all pass a check made before any is counted:
// those in flight hold a reservation, so the key goes over by about one
// call, not by N.
func TestKeyLimitHoldsParallelRequests(t *testing.T) {
fresh(t)
budget.Forget()
calls := limitedUpstream(t, 80*time.Millisecond)
keys, secrets := newCaller(t, "Busy")
setLimit(t, keys[0].ID, &access.Limit{Period: "month", Tokens: 2000})
h := New().Handler()
// a body of about the 300 tokens the call uses
body := `{"model":"plan/m1","messages":[{"role":"user","content":"` + strings.Repeat("x", 1130) + `"}]}`
call := func() int {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
if call() != 200 {
t.Fatal("first call")
}
var wg sync.WaitGroup
var ok, refused atomic.Int64
for range 20 {
wg.Go(func() {
switch call() {
case 200:
ok.Add(1)
case 429:
refused.Add(1)
}
})
}
wg.Wait()
st := budget.Of(access.Key{ID: keys[0].ID, Limit: &access.Limit{Period: "month", Tokens: 2000}}, time.Now())
if st.Tokens > 2000+350 || refused.Load() == 0 || ok.Load()+refused.Load() != 20 {
t.Fatalf("20 at once: %d let in, %d refused, %d tokens used of 2000, %d upstream calls", ok.Load(), refused.Load(), st.Tokens, calls.Load())
}
if st.InFlight != 0 || st.Reserved != 0 {
t.Fatal("reservations left behind", st)
}
if call() != 429 {
t.Fatal("spent key let in")
}
}
// A window ends at the calendar's: what was used today counts nothing
// tomorrow, and a call before the window started never counts.
func TestKeyLimitWindowResets(t *testing.T) {
fresh(t)
budget.Forget()
limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Daily")
lim := &access.Limit{Period: "day", Tokens: 350}
setLimit(t, keys[0].ID, lim)
// yesterday's call
budget.Append(usage.Record{Time: time.Now().AddDate(0, 0, -1), Provider: "plan", Model: "m1", Input: 5000, Status: 200, CallerKeyID: keys[0].ID})
h := New().Handler()
call := func() int {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
if call() != 200 {
t.Fatal("yesterday's use counted today")
}
if call() != 429 {
t.Fatal("spent key let in")
}
who := access.Identity{KeyID: keys[0].ID, KeyName: "Daily", Limit: lim}
if _, refused := budget.Reserve(who, 10, "", time.Now()); refused == nil {
t.Fatal("spent today")
}
_, reset := access.Window("day", time.Now())
release, refused := budget.Reserve(who, 10, "", reset.Add(time.Minute))
if refused != nil {
t.Fatal("tomorrow's window still spent", refused)
}
release()
}