Files
magpie/internal/gateway/budget_plugin_test.go
T
yetone a1f7b8c13f plugin: gateway key limits are the Key limits plugin on the gateway's budget point (P3)
The last P3 point, after observer, router strategy, middleware and tool:
the budget point (internal/gwbudget). A plugin serves a Limiter while it
is on; the gateway asks gwbudget.Limiting before any request of a key held
to a limit goes to a provider (reserveFor: the chat APIs' keyLimited, the
search MCP server and the vision one). A request without a key, or of a
key with no limit, never asks it.

It fails closed. A key with a limit and no limiter served gets 503
gateway_key_limit_off, X-Should-Retry false, nothing sent, and a rejected
usage row. With none served, Limiting first asks the gateway's refresh
(pluginrt.Refresh, at most once a second, never from inside one), so a
limit set a moment ago turns the plugin on for the request that needs it.
A limit reached is the 429 gateway_key_limit with Retry-After and
X-Magpie-Limit-Reset, as before.

plugins/budget serves internal/budget's limiter (budget.Limiter). It is
Essential and in use while a gateway key has a limit, so it can only be
off while none has; a keys file that can't be read is an error, so it
stays on. KeepFresh watches the keys file too. What a key has used and
has left (/v1/magpie/limit, the Gateway page, the CLI) and budget.Append
stay in the core, so the ledger counts a key's use the same either way,
and the key editor's limit fields stay, since setting a limit is what
turns the plugin back on.

The builtins GUI test wheels to the Routing row as it did to Usage's: the
new row puts it below the fold in WebKit, where the page puts back a
scroll that isn't the reader's (scrollOnPurpose).

Run at this head (on origin/main 9d97fd073):
- go test -count=1 -timeout 45m ./... at this head (after two runs cut short by a full disk): 63 ok, 1 red: internal/gui TestMainWindowCorners/macOS_26_SDK killed at its 40s deadline at load ~280 (#1936, no window change here); alone it passed.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestKeyLimitsOnAndOff, TestVisionMCPHeldToKeyLimit, TestKeyLimit*,
  plugins/budget tests

Broken by hand, each test went red: reserveFor ignoring Limiting's error,
Limiting letting a limited key through with none served, the refresh
never asked, Apply serving nothing, InUse counting keys with no limit,
InUse swallowing a read error, the vision and search MCP servers not
reserving, a refusal answered as 503 rather than 429.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3594, fake vendor on 3593, two gateway keys):
- no key with a limit: `plugin builtin off budget` turned it off; the
  key's request was 200
- `gateway-key limit <id> day --tokens 3`, then a request at once: 200,
  and the plugin read "on, in use"; the next 200, then 429 "has used 4 of
  its 3 ... tokens for this day"; turning it off was refused, "in use"
- the key with no limit: 200; /v1/magpie/limit answered the spent day
- limit removed: turned off; the key's request 200; a limit set again and
  a request at once: 200, "on, in use"
Not tried: the 503 in real use. With a key limited, the refresh turns the
plugin on before the request is refused (a hand-set `enabled: false` in
plugins.yml read "on, in use"); the 503 is the test's.
2026-10-15 18:41:03 +08:00

99 lines
3.5 KiB
Go

package gateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
)
// The budget point with plugins/budget on and off, for a key held to a
// limit beside one that isn't. On, the limited key is let in while it has
// something left and refused with a 429 after. Off, the limited key is
// refused with a 503 and nothing is sent, in the chat API and the search
// MCP server alike (the vision one: TestVisionMCPHeldToKeyLimit), and the
// refusal is recorded; the key
// with no limit and a keyless request from this computer go on as before.
// A refresh that turns the plugin on lets the limited key's next request
// in at once.
func TestKeyLimitsOnAndOff(t *testing.T) {
fresh(t)
budget.Forget()
pinLimitClock(t)
calls := limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Capped", "Free")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
s := New()
h := s.Handler()
call := func(secret string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
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
}
capped := access.Identity{KeyID: keys[0].ID, KeyName: "Capped", Limit: &access.Limit{Period: "day", Tokens: 700}}
mcp := func() error {
r := httptest.NewRequest("POST", SearchMCPPath, nil).WithContext(access.WithIdentity(t.Context(), capped))
_, err := s.searchMCPRun(r, "latest go")
return err
}
// on
if w := call(secrets[0]); w.Code != 200 {
t.Fatal("on: within the limit", w.Code, w.Body.String())
}
if w := call(secrets[0]); w.Code != 200 {
t.Fatal("on: within the limit", w.Code, w.Body.String())
}
if w := call(secrets[0]); w.Code != http.StatusTooManyRequests {
t.Fatal("on: a spent key let in", w.Code, w.Body.String())
}
if calls.Load() != 2 {
t.Fatalf("on: %d calls reached the provider", calls.Load())
}
// off
withoutLimits(t)
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 100000})
w := call(secrets[0])
if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Key limits plugin") || w.Header().Get("X-Should-Retry") != "false" {
t.Fatal("off: a limited key's request", w.Code, w.Body.String(), w.Header())
}
if calls.Load() != 2 {
t.Fatal("off: a limited key's request reached the provider")
}
if rec := lastUsage(t); !rec.Rejected || rec.CallerKeyID != keys[0].ID || rec.ErrType != "gateway_key_limit_off" || rec.Status != 503 {
t.Fatalf("off: refusal recorded as %+v", rec)
}
if err := mcp(); err == nil || !strings.Contains(err.Error(), "Key limits plugin") {
t.Errorf("off: the search MCP server said %v, not that the plugin is off", err)
}
if w := call(secrets[1]); w.Code != 200 {
t.Fatal("off: a key with no limit refused", w.Code, w.Body.String())
}
if w := call(""); w.Code != 200 {
t.Fatal("off: a keyless loopback request refused", w.Code, w.Body.String())
}
// the gateway's refresh turns it on for the request that needs it
var on func()
stop := gwbudget.Refresh(func() { on = gwbudget.Limit(budget.Limiter{}) })
defer stop()
gwbudget.ForgetRefreshForTest()
before := calls.Load()
if w := call(secrets[0]); w.Code != 200 || on == nil || calls.Load() != before+1 {
t.Fatal("a refresh that turned the plugin on still refused", w.Code, w.Body.String())
}
on()
}