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.
213 lines
7.2 KiB
Go
213 lines
7.2 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/agentenv"
|
|
"github.com/yetone/magpie/internal/budget"
|
|
"github.com/yetone/magpie/internal/gwbudget"
|
|
"github.com/yetone/magpie/internal/gwmw"
|
|
"github.com/yetone/magpie/internal/gwtool"
|
|
"github.com/yetone/magpie/internal/masking"
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/routes"
|
|
"github.com/yetone/magpie/internal/testenv"
|
|
)
|
|
|
|
// standInsEnv names the folder of a test binary's stand-in CLIs, for a
|
|
// test binary it starts again.
|
|
const standInsEnv = "MAGPIE_GATEWAY_TEST_STAND_INS"
|
|
|
|
func TestMain(m *testing.M) {
|
|
serveRotation()
|
|
groupsServed = provider.ServeGroups()
|
|
serveMiddleware()
|
|
searchOn = gwtool.Serve(gwtool.WebSearch)
|
|
limitsOn = gwbudget.Limit(budget.Limiter{})
|
|
code, err := isolatedTests(m)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
code = 1
|
|
}
|
|
os.Exit(code)
|
|
}
|
|
|
|
// Isolate every process, including the cold-start redaction tests. HOME
|
|
// alone does not isolate the macOS Keychain, and account caches eventually
|
|
// expire: discovery must keep finding only the test's sign-ins and CLIs.
|
|
func isolatedTests(m *testing.M) (int, error) {
|
|
home, err := os.MkdirTemp("", "magpie-gateway-test-")
|
|
if err != nil {
|
|
return 1, err
|
|
}
|
|
defer os.RemoveAll(home)
|
|
for name, value := range map[string]string{
|
|
"HOME": home, "USERPROFILE": home,
|
|
"XDG_CONFIG_HOME": filepath.Join(home, ".config"),
|
|
"XDG_CACHE_HOME": filepath.Join(home, ".cache"),
|
|
"XDG_DATA_HOME": filepath.Join(home, ".local", "share"),
|
|
"APPDATA": filepath.Join(home, "AppData", "Roaming"),
|
|
"LOCALAPPDATA": filepath.Join(home, "AppData", "Local"),
|
|
} {
|
|
if err := os.Setenv(name, value); err != nil {
|
|
return 1, err
|
|
}
|
|
}
|
|
// The package isolates itself rather than through testenv.Run, so it
|
|
// says so as testenv does: what reads the marker (a CLI identity kept
|
|
// on disk, provider.keepsIdentities; the machine's own folders,
|
|
// proc.SystemDirs) then acts as in any isolated test binary. Without it
|
|
// an ask still going when its test ended wrote cli-identity.json into
|
|
// the next test's folder as that was removed (#1524, again after
|
|
// 9c377231 dropped this package's own switch).
|
|
if err := os.Setenv(testenv.Marker, home); err != nil {
|
|
return 1, err
|
|
}
|
|
for _, name := range agentenv.Vars {
|
|
if err := os.Unsetenv(name); err != nil {
|
|
return 1, err
|
|
}
|
|
}
|
|
// The machine's proxy variables too: net/http freezes them into its
|
|
// first routed request, so a test that sets its own afterwards (search's
|
|
// Auto, by ALL_PROXY alone) reads the machine's instead, and its
|
|
// searcher goes out through a proxy that cannot reach the test's
|
|
// servers.
|
|
testenv.ClearProxy()
|
|
// The fakes of ChatGPT's backend read turns plain; codex_zstd_test's
|
|
// send them zstd, as the real one is sent.
|
|
provider.CodexZstdForTests(false)
|
|
// Finding an inert CLI also prevents discovery from falling back to
|
|
// one installed at an absolute system path. Tests can prepend their
|
|
// own fakes, as fakeClaude does, and still use ordinary shell tools.
|
|
// A test binary this one starts again (the cold-start redaction tests)
|
|
// runs the stand-ins its parent made: on macOS a newly written program
|
|
// waits for the system's first-run check, and under a full suite's load
|
|
// a child's account discovery spent its whole 20s on new stand-ins.
|
|
bin := os.Getenv(standInsEnv)
|
|
if bin == "" {
|
|
bin = filepath.Join(home, "bin")
|
|
if err := os.Mkdir(bin, 0o755); err != nil {
|
|
return 1, err
|
|
}
|
|
if err := testenv.StandIns(bin, []string{"security", "secret-tool", "claude", "codex", "cursor-agent", "devin", "grok", "kiro-cli"}); err != nil {
|
|
return 1, err
|
|
}
|
|
defer testenv.RemovePrograms()
|
|
if err := os.Setenv(standInsEnv, bin); err != nil {
|
|
return 1, err
|
|
}
|
|
}
|
|
if err := os.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")); err != nil {
|
|
return 1, err
|
|
}
|
|
// no route is written to disk behind a test's back; the history's own
|
|
// tests call saveRoute themselves
|
|
keepRoutes = false
|
|
// no test asks a vendor: a provider with a real base URL and a made-up
|
|
// key would, in the background (a plan key's windows, #1016), and a
|
|
// plugin host's first start fetched models.dev
|
|
testenv.Offline()
|
|
// and no rest waits on a reading in the background: it would ask a
|
|
// test's fake upstream after the test ended (#2036, CodeAlex52)
|
|
awaitAllowance = func(context.Context, string, string) bool { return false }
|
|
return m.Run(), nil
|
|
}
|
|
|
|
// The package's tests run as an isolated test binary: nothing the marker
|
|
// turns off (a CLI identity kept on disk, #1524) runs behind a test's back.
|
|
func TestRunsAsAnIsolatedTestBinary(t *testing.T) {
|
|
if os.Getenv(testenv.Marker) == "" {
|
|
t.Fatalf("TestMain left %s unset", testenv.Marker)
|
|
}
|
|
}
|
|
|
|
// rotation is what serveRotation registered: the routings plugins/rotation
|
|
// serves, which the gateway's tests route by as a user with it on does.
|
|
var rotation []func()
|
|
|
|
// masked and chained are the gateway's middleware point as
|
|
// plugins/redact and plugins/middleware serve it, on in every test but
|
|
// those of it off (withoutMasker, withoutMiddleware).
|
|
var masked, chained func()
|
|
|
|
func serveMiddleware() {
|
|
masked = gwmw.Mask(masking.Masker{})
|
|
chained = gwmw.Use(middleware.Chain{})
|
|
}
|
|
|
|
// withoutMasker takes the masker away for t, as plugins/redact off does.
|
|
func withoutMasker(t *testing.T) {
|
|
masked()
|
|
t.Cleanup(func() { masked = gwmw.Mask(masking.Masker{}) })
|
|
}
|
|
|
|
// withoutMiddleware takes the JS middleware chain away for t, as
|
|
// plugins/middleware off does.
|
|
func withoutMiddleware(t *testing.T) {
|
|
chained()
|
|
t.Cleanup(func() { chained = gwmw.Use(middleware.Chain{}) })
|
|
}
|
|
|
|
func serveRotation() {
|
|
for name, s := range routes.Builtin {
|
|
rotation = append(rotation, routes.Register(name, s))
|
|
}
|
|
}
|
|
|
|
// withoutRotation takes them away for t, as plugins/rotation off does.
|
|
func withoutRotation(t *testing.T) {
|
|
for _, remove := range rotation {
|
|
remove()
|
|
}
|
|
rotation = nil
|
|
t.Cleanup(serveRotation)
|
|
}
|
|
|
|
// groupsServed is plugins/groups on, as for a user with a group of their
|
|
// own: the gateway's tests serve their groups.
|
|
var groupsServed func()
|
|
|
|
// withoutGroups is plugins/groups off for t, in a process serving the
|
|
// gateway (provider.GateGroups): the user's own groups aren't served.
|
|
func withoutGroups(t *testing.T) {
|
|
groupsServed()
|
|
stop := provider.GateGroups(nil)
|
|
t.Cleanup(func() {
|
|
stop()
|
|
groupsServed = provider.ServeGroups()
|
|
})
|
|
}
|
|
|
|
// searchOn is plugins/search on: the gateway's tests offer and answer
|
|
// magpie's web search, as a user with it on has.
|
|
var searchOn func()
|
|
|
|
// limitsOn is plugins/budget on: the gateway's tests hold gateway keys to
|
|
// their limits, as a user with it on has.
|
|
var limitsOn func()
|
|
|
|
// withoutLimits is plugins/budget off for t, with no refresh to turn it
|
|
// on: a key held to a limit is refused with nothing sent.
|
|
func withoutLimits(t *testing.T) {
|
|
limitsOn()
|
|
t.Cleanup(func() { limitsOn = gwbudget.Limit(budget.Limiter{}) })
|
|
}
|
|
|
|
// withoutSearch is plugins/search off for t, in a process serving the
|
|
// gateway (gwtool.Gate): magpie's web search is neither offered nor
|
|
// answered.
|
|
func withoutSearch(t *testing.T) {
|
|
searchOn()
|
|
stop := gwtool.Gate()
|
|
t.Cleanup(func() {
|
|
stop()
|
|
searchOn = gwtool.Serve(gwtool.WebSearch)
|
|
})
|
|
}
|