diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f420d0654..ae8026c32 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -729,6 +729,35 @@ prefers a whole-key limit, and a remote's key card leaves such limits out asks it with each of its remote-magpie keys for that key's card on its Usage page (#1547), a window per limit's cap. +A key's `MaxConcurrency` (young02036 on Discord; `access.Key`, set by the +`concurrency-key` action, the key row's "at once" badge or `magpie +gateway-key concurrency |off`, 0 to 1000, 0 or unset for no limit) +is how many of its requests are in flight at once. One more waits in the +key's own lane (`keyLanes`, apart from the providers' `lanes`, by +`"key:"+id`), in order and with no bound, shows as `slot` in Active and the +trace, and has its wait in its try's `Queued`; one whose agent goes away +while it waits leaves the queue and sends nothing. A key issued under +another (`access.Identity.Issuer`) waits for a slot of its own, then one of +its issuer's. `keySlots` sits in `Handler` after `withCaller` and `keyLimited`, so the +LAN, a remote magpie and each turn of a Responses socket (sent through the +handler again) all pass it; `keySlotRoutes` names the routes it holds, and +`TestKeySlotEveryRoute` fails on a route judged neither held nor free +(`keySlotFree`: GETs, count_tokens, MCP, magpie's own). The routes that go +through `serve`'s tries (chat, Responses, Messages, Ollama, Gemini, the Codex +backend) take the slot in the try, after `keepQueued`, so a waiting stream +gets its 200 and keepalive comments as it does waiting for a provider's +slot; the rest (embeddings, images, audio, videos, rerank, decisions, System +One, native) take it before their handler runs. `forward` and +`codexUpstreamOn` take it too, so no path of a held route reaches a vendor +unheld. The slot is the request's until its handler returns, a stream's to +its end; a later take within the same request takes nothing more (`keyHold`). +`/v1/magpie/concurrency` reports the keys' lanes under `keys` and counts +their waiters in `waiting`; `/v1/magpie/limit` says the key's +`maxConcurrency` and `issuerMaxConcurrency`. Tests: `TestKeyConcurrency*` +and `TestKeySlotEveryRoute` in `key_slots_test.go`, `TestKeyConcurrency` in +`internal/access`, `TestGatewayKeyConcurrencyCLI`, +`gateway-key-concurrency.test.cjs`. + `GET /me` is the key page: a gateway key's holder opens it in a browser at the address they reach the gateway at, types their key, and sees that key's own name, limits, usage (today, 7 and 30 days, its most used models) and diff --git a/internal/access/access.go b/internal/access/access.go index 640c19e04..84f00743e 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -182,8 +182,17 @@ type Key struct { // Issues lets the key issue short-lived keys under itself // (POST /v1/magpie/keys); an issued key never can. Issues bool `json:"issues,omitempty"` + // MaxConcurrency is how many of the key's requests may be in flight + // at once (young02036 on Discord); over it they wait in the key's + // queue and go out in order, as over a provider's MaxConcurrency. + // 0 for no limit. + MaxConcurrency int `json:"maxConcurrency,omitempty"` } +// MaxKeyConcurrency is the most MaxConcurrency a key may have, as a +// provider's. +const MaxKeyConcurrency = 1000 + // Identity is the gateway key a request came with, its budget, the // models and the accounts it may use. type Identity struct { @@ -218,6 +227,10 @@ type Identity struct { Issuer *Identity // Issues: the key may issue keys under itself. Issues bool + // MaxConcurrency is the key's own cap on requests in flight at once + // (Key.MaxConcurrency), 0 for none; an issued key is held to its + // issuer's too (Issuer.MaxConcurrency). + MaxConcurrency int // Default: the key is the sharing key magpie made itself (Default), // the one it writes into this computer's own agents that reach the // gateway from beyond loopback, never one the user made for someone @@ -422,6 +435,9 @@ type Change struct { // Issues is what "issuer-key" sets: the key may issue short-lived // keys under itself (Key.Issues). Issues bool `json:"issues,omitempty"` + // MaxConcurrency is what "concurrency-key" sets: how many requests + // the key may have in flight at once, 0 for no limit. + MaxConcurrency int `json:"maxConcurrency,omitempty"` // Secret is the value "add-key" gives the new key, one its clients // already send (love1sbug on X: keys handed out from another gateway), // or "rotate-key" gives the key; "" for one magpie makes. @@ -581,6 +597,11 @@ func Update(action string, in Change) (string, error) { keys[i].MCP = mcp case "quotas-key": keys[i].Quotas = in.Quotas + case "concurrency-key": + if in.MaxConcurrency < 0 || in.MaxConcurrency > MaxKeyConcurrency { + return "", fmt.Errorf("Concurrency: a whole number from 0 to %d", MaxKeyConcurrency) + } + keys[i].MaxConcurrency = in.MaxConcurrency case "issuer-key": // may issue short-lived keys under itself (POST /v1/magpie/keys) if in.Issues && keys[i].Browser { @@ -626,7 +647,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/concurrency_test.go b/internal/access/concurrency_test.go new file mode 100644 index 000000000..5c4552d6f --- /dev/null +++ b/internal/access/concurrency_test.go @@ -0,0 +1,81 @@ +package access + +import ( + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/settings" +) + +// young02036 on Discord: a gateway key gets a cap on its requests in +// flight, as a provider has. concurrency-key sets it, Authenticate tells +// it, 0 takes it off, a value outside 0..1000 is refused and the key is +// left as it was, and an issued key is told its issuer's cap too. +func TestKeyConcurrency(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clockAt(t, time.Date(2026, 11, 8, 9, 0, 0, 0, time.UTC)) + id, secret := addKey(t, "Team") + if who, _ := Authenticate(secret); who.MaxConcurrency != 0 { + t.Fatal("a new key has a cap:", who.MaxConcurrency) + } + if _, err := Update("concurrency-key", Change{Key: id, MaxConcurrency: 3}); err != nil { + t.Fatal(err) + } + if who, ok := Authenticate(secret); !ok || who.MaxConcurrency != 3 { + t.Fatal("set 3:", who.MaxConcurrency, ok) + } + keys, _ := List() + if keys[0].MaxConcurrency != 3 { + t.Fatal("listed:", keys[0].MaxConcurrency) + } + for _, bad := range []int{-1, 1001} { + if _, err := Update("concurrency-key", Change{Key: id, MaxConcurrency: bad}); err == nil || !strings.Contains(err.Error(), "0 to 1000") { + t.Fatal(bad, err) + } + } + if who, _ := Authenticate(secret); who.MaxConcurrency != 3 { + t.Fatal("a refused value changed the key:", who.MaxConcurrency) + } + + // issued under it: its own cap, and its issuer's + if _, err := Update("issuer-key", Change{Key: id, Issues: true}); err != nil { + t.Fatal(err) + } + child, err := IssueKey(Issue{TTL: time.Hour, Issuer: id}) + if err != nil { + t.Fatal(err) + } + if _, err := Update("concurrency-key", Change{Key: child.ID, MaxConcurrency: 5}); err != nil { + t.Fatal(err) + } + who, ok := Authenticate(child.Key) + if !ok || who.MaxConcurrency != 5 || who.Issuer == nil || who.Issuer.MaxConcurrency != 3 { + t.Fatal("issued:", who, ok) + } + + if _, err := Update("concurrency-key", Change{Key: id}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(secret); who.MaxConcurrency != 0 { + t.Fatal("0 left a cap:", who.MaxConcurrency) + } + + // the sharing key takes a cap without its settings mirror being + // written again + s := settings.Load() + s.LANKeyID = id + s.LANKey = secret + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if _, err := Update("concurrency-key", Change{Key: id, MaxConcurrency: 2}); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.LANKey != secret || got.LANKeyID != id { + t.Fatal("the mirror was rewritten:", got.LANKeyID) + } + if who, _ := Authenticate(secret); who.MaxConcurrency != 2 || !who.Default { + t.Fatal("the sharing key:", who.MaxConcurrency, who.Default) + } +} diff --git a/internal/access/issue.go b/internal/access/issue.go index e404b4a80..3090162e3 100644 --- a/internal/access/issue.go +++ b/internal/access/issue.go @@ -320,7 +320,7 @@ func ScopeBrowser(id string) error { // identityOf is who k is, folded into its issuer when it has one. func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { - who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser} + who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency} // the default key as Default tells it: marked LAN, or the id the // settings name (settings read only for an unmarked key) who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID) @@ -346,7 +346,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) { who.Expires = p.Expires } - who.Issuer = &Identity{KeyID: p.ID, KeyName: p.Name, Limit: p.Limit, More: p.More, MCP: p.MCP} + who.Issuer = &Identity{KeyID: p.ID, KeyName: p.Name, Limit: p.Limit, More: p.More, MCP: p.MCP, MaxConcurrency: p.MaxConcurrency} return who, nil } diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 4ba1d6fb8..b8e9a1a64 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -43,6 +43,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyQuotas(out, args[1:]) } + if action == "concurrency" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyConcurrency(out, args[1:]) + } if action == "mcp" { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyMCP(out, args[1:]) @@ -96,7 +100,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -628,6 +632,52 @@ func gatewayKeyQuotas(out io.Writer, args []string) error { return err } +// gatewayKeyConcurrency shows or sets how many of a key's requests may +// be in flight at once (young02036 on Discord); one more waits its turn, +// as over a provider's concurrency: +// +// magpie gateway-key concurrency its cap, or none +// magpie gateway-key concurrency |off at most n at once, or no cap +func gatewayKeyConcurrency(out io.Writer, args []string) error { + usage := fmt.Errorf("usage: magpie gateway-key concurrency [ | off], n a whole number from 1 to %d", access.MaxKeyConcurrency) + if len(args) == 0 || len(args) > 2 { + return usage + } + id := args[0] + if len(args) == 2 { + n := 0 + if args[1] != "off" { + v, err := strconv.Atoi(args[1]) + if err != nil || v < 1 || v > access.MaxKeyConcurrency { + return usage + } + n = v + } + if _, err := access.Update("concurrency-key", access.Change{Key: id, MaxConcurrency: n}); err != nil { + return err + } + } + keys, err := access.List() + if err != nil { + return err + } + i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id }) + if i < 0 { + return fmt.Errorf("Key not found") + } + k := keys[i] + if k.MaxConcurrency > 0 { + reqs := "requests" + if k.MaxConcurrency == 1 { + reqs = "request" + } + _, err = fmt.Fprintf(out, "%s: at most %d %s at once, the rest wait their turn\n", k.Name, k.MaxConcurrency, reqs) + } else { + _, err = fmt.Fprintf(out, "%s: no concurrency limit\n", k.Name) + } + return err +} + // accessWord is a key's access as the list says it: "browser" (Magpie // Browser's, access.Key.Browser), "read-only" or "full". func accessWord(k access.Key) string { diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index f68c5add3..72eb043c6 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -596,3 +596,56 @@ func TestGatewayKeyMCPCLI(t *testing.T) { t.Fatal("all kept", keys[0].MCP) } } + +// young02036 on Discord: a key's concurrency is set, shown and turned off +// from the CLI; a value that isn't a whole number from 1 to the most is +// refused and changes nothing, and --help names the command. +func TestGatewayKeyConcurrencyCLI(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + if _, err := call("add", "Team"); err != nil { + t.Fatal(err) + } + keys, _ := access.List() + id := keys[0].ID + if got, err := call("concurrency", id); err != nil || got != "Team: no concurrency limit\n" { + t.Fatal(got, err) + } + if got, err := call("concurrency", id, "3"); err != nil || got != "Team: at most 3 requests at once, the rest wait their turn\n" { + t.Fatal(got, err) + } + if got, err := call("concurrency", id, "1"); err != nil || got != "Team: at most 1 request at once, the rest wait their turn\n" { + t.Fatal(got, err) + } + if _, err := call("concurrency", id, "3"); err != nil { + t.Fatal(err) + } + for _, args := range [][]string{{"concurrency"}, {"concurrency", id, "0"}, {"concurrency", id, "-1"}, {"concurrency", id, "1001"}, + {"concurrency", id, "2.5"}, {"concurrency", id, "two"}, {"concurrency", id, "--help"}, {"concurrency", id, "3", "4"}, + {"concurrency", "missing", "3"}, {"concurrency", "missing"}} { + if _, err := call(args...); err == nil { + t.Error("accepted", args) + } + } + if keys, _ = access.List(); keys[0].MaxConcurrency != 3 { + t.Fatalf("a refused call changed it: %d", keys[0].MaxConcurrency) + } + if got, err := call("concurrency", id, "off"); err != nil || got != "Team: no concurrency limit\n" { + t.Fatal(got, err) + } + if keys, _ = access.List(); keys[0].MaxConcurrency != 0 { + t.Fatal("not turned off") + } + if help := helpFor([]string{"gateway-key", "concurrency", "--help"}); !strings.Contains(help, "gateway-key concurrency [|off]") { + t.Fatal(help) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index e2a583a3e..14ba5bbe5 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -135,6 +135,7 @@ const usage = `magpie — one place to pick every agent's model magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads --model openai/*] a key's own limits, and what it used; --model counts only those models magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some magpie gateway-key quotas [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use + magpie gateway-key concurrency [|off] at most n of a key's requests at once; the rest wait their turn magpie gateway-key mcp [all|none||/ ...] the MCP servers and tools a key may use magpie gateway-key access [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write magpie gateway-key move put a key at a place in the list (from 1), the order list and the app show them in diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 286147752..8f268a140 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -947,6 +947,11 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri // codexUpstreamOn is codexUpstream signed by the account on instead of // Codex's own sign-in, when on isn't nil (compactOn). func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest string, body []byte, on *provider.Provider) { + // a gateway key's turn on Codex's own sign-in waits for its key's slot + // here, outside serve (key_slots.go); its agent gone, nothing is sent + if _, err := keySlot(r.Context()); err != nil { + return + } start := time.Now() usage.Saw(agentOf(r)) // Codex's own turns come here from the mux, not through serve: the diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index 1eccbd177..db3a469bb 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -493,8 +493,13 @@ func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) { for _, ln := range lanes { waiting += ln.Waiting } + // and those waiting for a slot of their gateway key's (key_slots.go) + keys := s.KeyLanes() + for _, ln := range keys { + waiting += ln.Waiting + } b := s.Busy() - writeJSON(w, 200, map[string]any{"object": "concurrency", "data": lanes, "requests": b.Requests, "waiting": waiting, "tools": b.Tools, "active": s.Active()}) + writeJSON(w, 200, map[string]any{"object": "concurrency", "data": lanes, "requests": b.Requests, "keys": keys, "waiting": waiting, "tools": b.Tools, "active": s.Active()}) } // Lanes is how each key or account with requests out or waiting stands, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2ec9eff8c..f7ece3688 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -557,6 +557,9 @@ type Server struct { // the requests out at each key or account with a MaxConcurrency, and // those waiting their turn (concurrency.go) lanes lanes + // the requests in flight of each gateway key with a MaxConcurrency, + // and those waiting their turn (key_slots.go) + keyLanes lanes // each account's one turn at a time near its usage cap (cap_near.go) nearCap nearCaps // the requests each key or account with a MaxRPM sent in the last @@ -937,7 +940,7 @@ func (s *Server) Handler() http.Handler { // on (dumpFirst) // a socket's turns go through all of it again (socketEntry); the // agent's Retry-After is bounded on the way out (retryCapped) - return socketEntry(s.dumpFirst(retryCapped(s.counted(headerLogged(holdCatalog(corsGuard(callerGuard(readOnlyGuard(mux, withCaller(keyLimited(mux))))))))))) + return socketEntry(s.dumpFirst(retryCapped(s.counted(headerLogged(holdCatalog(corsGuard(callerGuard(readOnlyGuard(mux, withCaller(keyLimited(s.keySlots(mux, mux)))))))))))) } // routes are the client APIs, each by its pattern: readOnlyGuard reads @@ -3816,14 +3819,16 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro queuedAlive := hw.keepQueued() var release func() var inLane time.Duration - var err error var mate candidate - if handed.release != nil { + // the slot of its gateway key's first, once for the request + // (key_slots.go): its agent gone meanwhile, nothing is sent + inKey, err := keySlot(ctx) + if err == nil && handed.release != nil { // it left a full lane's queue for this one, whose slot it // took as it did (waitMate): the wait there is its queue release, handed.release = handed.release, nil inLane, handed.waited = handed.waited, 0 - } else { + } else if err == nil { // waiting, it goes to the first other key or account with // room, not resting, once there is one (01huadalang on // Discord: the requests already waiting for a third ZCode @@ -3847,7 +3852,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if firstBegan.Equal(began) { // the first try's wait is the next one's queue, not a // failed try's time - firstBegan, handed.waited = time.Time{}, inLane + firstBegan, handed.waited = time.Time{}, inKey+inLane } gaveWay[c.who()] = true cands = movedAhead(cands, i, mate) @@ -3866,7 +3871,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } } queuedAlive() - queued = (inLane + inMinute).Milliseconds() + queued = (inKey + inLane + inMinute).Milliseconds() var tooMany *errRPM if errors.Is(err, errQueueFull) || errors.Is(err, errQueueWait) || errors.As(err, &tooMany) { laneErr = err @@ -5490,6 +5495,11 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P heardNet() // the network is up (offline.go) } }() + // a way of a key's request that asks outside serve's tries waits for + // the key's slot here (key_slots.go); taken already, it goes on + if _, err := keySlot(ctx); err != nil { + return nil, err + } if p.ImageFilesAt(to) { // which images a try named by file (deepseek_files.go) ctx = context.WithValue(ctx, dsSentKey{}, &dsSent{}) diff --git a/internal/gateway/key_limit.go b/internal/gateway/key_limit.go index e912f9bac..56950dd3a 100644 --- a/internal/gateway/key_limit.go +++ b/internal/gateway/key_limit.go @@ -213,6 +213,14 @@ func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) { if !who.Expires.IsZero() { out["expires"] = who.Expires } + // "maxConcurrency", how many of its requests may be in flight at once + // (key_slots.go), and its issuer's + if who.KeyID != "" && who.MaxConcurrency > 0 { + out["maxConcurrency"] = who.MaxConcurrency + } + if who.KeyID != "" && who.Issuer != nil && who.Issuer.MaxConcurrency > 0 { + out["issuerMaxConcurrency"] = who.Issuer.MaxConcurrency + } if who.KeyID == "" || len(who.Limits()) == 0 { writeJSON(w, 200, out) return diff --git a/internal/gateway/key_slots.go b/internal/gateway/key_slots.go new file mode 100644 index 000000000..ded3e8410 --- /dev/null +++ b/internal/gateway/key_slots.go @@ -0,0 +1,218 @@ +package gateway + +import ( + "context" + "net/http" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/access" +) + +// A gateway key's MaxConcurrency (young02036 on Discord: providers have +// one, keys should too) is how many of its requests may be in flight at +// once. One more waits in the key's queue, in the order it came, with no +// bound, as over a provider's MaxConcurrency (concurrency.go): it reads as +// waiting for a slot ("slot") in Active, and what it waited is its try's +// Queued. Its agent gone while it waits, it leaves the queue and nothing +// is sent. A slot is held until the handler returns: a stream's to its +// end. A key issued under another (issue.go) waits for a slot of its own, +// then one of its issuer's, so the keys it issues hold no more at once +// than it does. With no cap nothing is counted or waited. +// +// Every route that asks a model is held, whichever way the request came +// (the LAN, a Remote magpie, a socket's turn): keySlots sits in Handler +// beside keyLimited, which each of them passes. keySlotRoutes names those +// routes; TestKeySlotEveryRoute fails on a route judged neither way. +// count_tokens isn't held, as a provider's MaxConcurrency doesn't count +// it, nor MCP, nor a GET (a poll, a list). +// +// A route whose requests go through serve's tries (lazy) waits there, in +// the try (keySlot), so a streaming agent is kept alive as it is while it +// waits for a provider's slot (keepQueued); the others (eager) wait before +// their handler begins. A way of a lazy route that asks upstream outside a +// try (forward, codexUpstreamOn) waits there, so nothing reaches a vendor +// unheld. + +// keySlotKind is how a route waits for its key's slot. +type keySlotKind int + +const ( + keySlotEager keySlotKind = iota + 1 + keySlotLazy +) + +// keySlotRoutes are the routes, by pattern, whose requests are held to +// their key's MaxConcurrency, and how; every other route of routes() is in +// keySlotFree (key_slots_test.go). +var keySlotRoutes = map[string]keySlotKind{ + "POST /v1/chat/completions": keySlotLazy, + "POST /chat/completions": keySlotLazy, + "POST /v1/responses": keySlotLazy, + "POST /responses": keySlotLazy, + "POST /v1/messages": keySlotLazy, + "POST /messages": keySlotLazy, + "POST /api/chat": keySlotLazy, + "POST /api/generate": keySlotLazy, + "POST /v1beta/models/{call...}": keySlotLazy, + CodexPath + "/": keySlotLazy, + "POST /v1/systemone": keySlotEager, + "POST /v1" + AlphaSearchPath: keySlotEager, + "POST " + AlphaSearchPath: keySlotEager, + "POST /v1/images/generations": keySlotEager, + "POST /images/generations": keySlotEager, + "POST /v1/images/edits": keySlotEager, + "POST /images/edits": keySlotEager, + "POST /v1/embeddings": keySlotEager, + "POST /embeddings": keySlotEager, + "POST /v1/rerank": keySlotEager, + "POST /rerank": keySlotEager, + "POST /v1/decisions": keySlotEager, + "POST /decisions": keySlotEager, + "POST /v1/audio/transcriptions": keySlotEager, + "POST /audio/transcriptions": keySlotEager, + "POST /v1/audio/translations": keySlotEager, + "POST /audio/translations": keySlotEager, + "POST /v1/audio/speech": keySlotEager, + "POST /audio/speech": keySlotEager, + "POST /v1/videos": keySlotEager, + "POST /videos": keySlotEager, + "POST " + NativePath + "{provider}/{path...}": keySlotEager, + "PUT " + NativePath + "{provider}/{path...}": keySlotEager, + "PATCH " + NativePath + "{provider}/{path...}": keySlotEager, + "DELETE " + NativePath + "{provider}/{path...}": keySlotEager, +} + +// keyCapped says whether who's key, or the one it was issued under, has a +// MaxConcurrency. +func keyCapped(who access.Identity) bool { + return who.MaxConcurrency > 0 || who.Issuer != nil && who.Issuer.MaxConcurrency > 0 +} + +// keySlots holds each request of a key with a MaxConcurrency to it, on +// the routes keySlotRoutes names. +func (s *Server) keySlots(mux *routeMux, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + who := access.Caller(r.Context()) + if !keyCapped(who) || r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions || strings.HasSuffix(r.URL.Path, ":countTokens") { + next.ServeHTTP(w, r) + return + } + _, pattern := mux.Handler(r) + kind := keySlotRoutes[pattern] + if kind == 0 { + next.ServeHTTP(w, r) + return + } + h := &keyHold{s: s, who: who, turn: make(chan struct{}, 1)} + defer h.release() + if kind == keySlotEager { + if _, err := h.take(r.Context()); err != nil { + return // its agent went away while it waited: nothing was sent + } + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), keyHoldKey{}, h))) + }) +} + +type keyHoldKey struct{} + +// keyHold is one request's slot in its key's lane, and its issuer's. +type keyHold struct { + s *Server + who access.Identity + // turn is held by the one taking the slot, so two parts of a request + // asking at once take one slot between them; it waits on no lock + // release needs + turn chan struct{} + + mu sync.Mutex + held bool + closed bool // the request is done: what is taken after goes back at once + rels []func() +} + +// take waits for the request's slot, once: taken already, or the request +// done, it returns at once. waited is how long it stood in the queues; err +// is ctx's when it ended first, with nothing taken, and a later take +// waits again. +func (h *keyHold) take(ctx context.Context) (waited time.Duration, err error) { + select { + case h.turn <- struct{}{}: + case <-ctx.Done(): + return 0, ctx.Err() + } + defer func() { <-h.turn }() + h.mu.Lock() + done := h.held || h.closed + h.mu.Unlock() + if done { + return 0, nil + } + var rels []func() + for _, k := range []*access.Identity{&h.who, h.who.Issuer} { + if k == nil || k.MaxConcurrency <= 0 { + continue + } + rel, w, err := h.s.keyLanes.take(ctx, keyLane(k.KeyID), k.MaxConcurrency, 0, 0, nil) + waited += w + if err != nil { + for _, f := range rels { + f() + } + return waited, err + } + rels = append(rels, rel) + } + h.mu.Lock() + if h.closed { + h.mu.Unlock() + for _, f := range rels { + f() + } + return waited, nil + } + h.held, h.rels = true, rels + h.mu.Unlock() + return waited, nil +} + +// release gives the slots back, once the request is done. +func (h *keyHold) release() { + h.mu.Lock() + h.closed = true + rels := h.rels + h.rels = nil + h.mu.Unlock() + for _, f := range rels { + f() + } +} + +// keyLane is a gateway key's lane in keyLanes, apart from every +// provider's. +func keyLane(id string) string { return "key:" + id } + +// keySlot waits for the slot of the key ctx's request came with, when +// its route holds it (keySlots) and it isn't taken yet; 0 and nil when +// there is none to wait for. +func keySlot(ctx context.Context) (time.Duration, error) { + h, _ := ctx.Value(keyHoldKey{}).(*keyHold) + if h == nil { + return 0, nil + } + return h.take(ctx) +} + +// KeyLanes is how each gateway key with a MaxConcurrency stands, by its +// id: its requests in flight and those waiting their turn. +func (s *Server) KeyLanes() map[string]Lane { + s.keyLanes.mu.Lock() + defer s.keyLanes.mu.Unlock() + out := map[string]Lane{} + for who, ln := range s.keyLanes.m { + out[strings.TrimPrefix(who, "key:")] = Lane{Busy: ln.busy, Waiting: len(ln.queue), Limit: ln.limit} + } + return out +} diff --git a/internal/gateway/key_slots_test.go b/internal/gateway/key_slots_test.go new file mode 100644 index 000000000..4464c790f --- /dev/null +++ b/internal/gateway/key_slots_test.go @@ -0,0 +1,313 @@ +package gateway + +import ( + "bufio" + "context" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// keySlotFree are the routes, other than a GET's or an OPTIONS' (never +// held), that a key's MaxConcurrency doesn't hold: magpie's own, MCP (a +// tool call of a turn already held) and count_tokens. A route in neither +// this nor keySlotRoutes fails TestKeySlotEveryRoute, so a new one is +// judged. +var keySlotFree = []string{ + "POST /api/show", "POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath, + "POST " + provider.RemoteCodexResetPath, "POST " + StatuslinePath, "POST " + KeysPath, + "DELETE " + KeysPath + "/{id}", "POST " + OIDCKeysPath, "POST " + provider.RemoteProvePath, + "POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens", + "POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath, + ImageMCPPath, BrowserMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}", + HubMCPPath + "{agent}", HubMCPAll, "/", +} + +// Every route is judged for a key's MaxConcurrency: held (keySlotRoutes) +// or not (keySlotFree, or a GET's), never both, and keySlotRoutes names +// only routes the router has. +func TestKeySlotEveryRoute(t *testing.T) { + fresh(t) + mux := New().routes() + for _, p := range mux.patterns { + _, held := keySlotRoutes[p] + free := slices.Contains(keySlotFree, p) || strings.HasPrefix(p, "GET ") || strings.HasPrefix(p, "OPTIONS ") + if held == free { + t.Errorf("route %q is in neither keySlotRoutes nor keySlotFree, or in both: say whether a gateway key's MaxConcurrency holds it", p) + } + } + for p := range keySlotRoutes { + if !slices.Contains(mux.patterns, p) { + t.Errorf("keySlotRoutes names %q, which the router doesn't have", p) + } + } + for _, p := range keySlotFree { + if !slices.Contains(mux.patterns, p) { + t.Errorf("keySlotFree names %q, which the router doesn't have", p) + } + } +} + +// lanServer serves s as it is to another computer on the LAN. +func lanServer(t *testing.T, s *Server) *httptest.Server { + h := lanGuard(s.Handler()) + gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.RemoteAddr = "192.168.1.9:5000" + h.ServeHTTP(w, r) + })) + t.Cleanup(gw.Close) + return gw +} + +// keyCap gives the key id a MaxConcurrency of n. +func keyCap(t *testing.T, id string, n int) { + t.Helper() + if _, err := access.Update("concurrency-key", access.Change{Key: id, MaxConcurrency: n}); err != nil { + t.Fatal(err) + } +} + +// young02036 on Discord: a gateway key with a MaxConcurrency of 2 has no +// more than two requests at the vendor at once, from another computer on +// the LAN. A third waits in the key's queue, shown as waiting for a slot, +// and goes once one before it is read to its end; one whose agent hangs +// up while it waits leaves the queue and never reaches the vendor; another +// key isn't held by it; and the wait is the try's Queued. +func TestKeyConcurrency(t *testing.T) { + fresh(t) + v := &slowVendor{release: map[string]chan struct{}{}, quit: make(chan struct{})} + up := httptest.NewServer(v) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Team", "Other") + team, other := keys[0], keys[1] + keyCap(t, team.ID, 2) + s := New() + gw := lanServer(t, s) + t.Cleanup(func() { close(v.quit) }) + + lane := func() Lane { return s.KeyLanes()[team.ID] } + type reply struct { + tag, body string + err error + } + replies := make(chan reply, 10) + send := func(ctx context.Context, secret, tag string) { + body := `{"model":"slow/m","stream":true,"messages":[{"role":"user","content":"` + tag + `"}]}` + go func() { + req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+"/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+secret) + res, err := http.DefaultClient.Do(req) + if err != nil { + replies <- reply{tag: tag, err: err} + return + } + b, err := io.ReadAll(res.Body) + res.Body.Close() + replies <- reply{tag, string(b), err} + }() + } + + send(context.Background(), secrets[0], "a") + within(t, "a at the vendor", func() bool { return len(v.seen()) == 1 }) + send(context.Background(), secrets[0], "b") + within(t, "b at the vendor", func() bool { return len(v.seen()) == 2 }) + send(context.Background(), secrets[0], "c") + within(t, "c queued", func() bool { return lane().Waiting == 1 }) + if l := lane(); l.Busy != 2 || l.Limit != 2 { + t.Fatalf("key lane = %+v, want 2 out, 1 waiting", l) + } + if !slices.ContainsFunc(s.Active(), func(a Active) bool { return a.Phase == "slot" }) { + t.Fatalf("no request shows waiting for a slot: %+v", s.Active()) + } + + // another key isn't held by this one's + send(context.Background(), secrets[1], "other") + within(t, "the other key's at the vendor", func() bool { return slices.Contains(v.seen(), "other") }) + close(v.gate("other")) + if r := <-replies; r.tag != "other" || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("the other key's reply = %+v", r) + } + if _, ok := s.KeyLanes()[other.ID]; ok { + t.Fatal("a key with no cap has a lane") + } + + // gone while it waits: out of the queue, never sent + ctx, cancel := context.WithCancel(context.Background()) + send(ctx, secrets[0], "gone") + within(t, "gone queued", func() bool { return lane().Waiting == 2 }) + cancel() + within(t, "gone out of the queue", func() bool { return lane().Waiting == 1 }) + if r := <-replies; r.tag != "gone" || r.err == nil { + t.Fatalf("the canceled request answered: %+v", r) + } + + // c goes only once a is read to its end, and then the slot of the + // stream it holds is the key's until it ends + time.Sleep(50 * time.Millisecond) + if slices.Contains(v.seen(), "c") { + t.Fatal("c reached the vendor with two out") + } + close(v.gate("a")) + if r := <-replies; r.tag != "a" || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("a = %+v", r) + } + within(t, "c at the vendor", func() bool { return slices.Contains(v.seen(), "c") }) + if l := lane(); l.Busy != 2 || l.Waiting != 0 { + t.Fatalf("key lane after a = %+v, want 2 out", l) + } + for _, tag := range []string{"b", "c"} { + close(v.gate(tag)) + if r := <-replies; r.err != nil || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("%s = %+v", tag, r) + } + } + if got := v.seen(); slices.Contains(got, "gone") { + t.Fatalf("the canceled request reached the vendor: %v", got) + } + within(t, "every key slot given back", func() bool { return len(s.KeyLanes()) == 0 }) + + // c's wait is its try's Queued + var queued int64 + for _, rt := range s.Trace(context.Background(), 0, 0).Routes { + for _, tr := range rt.Tries { + queued = max(queued, tr.Queued) + } + } + if queued < 40 { + t.Fatalf("the queued try's Queued = %dms, want its wait", queued) + } +} + +// A stream waiting for its key's slot past keepHeldAfter is sent its 200 +// and SSE comments meanwhile, as one waiting for a provider's slot is +// (keepQueued): its agent's timeout for headers doesn't end it. +func TestKeyConcurrencyKeepsStreamAlive(t *testing.T) { + fresh(t) + k, e := keepHeldAfter, watchEvery + keepHeldAfter, watchEvery = 10*time.Millisecond, 10*time.Millisecond + t.Cleanup(func() { keepHeldAfter, watchEvery = k, e }) + v := &slowVendor{release: map[string]chan struct{}{}, quit: make(chan struct{})} + up := httptest.NewServer(v) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Team") + keyCap(t, keys[0].ID, 1) + s := New() + gw := lanServer(t, s) + t.Cleanup(func() { close(v.quit) }) + post := func(tag string) *http.Response { + body := `{"model":"slow/m","stream":true,"messages":[{"role":"user","content":"` + tag + `"}]}` + req, _ := http.NewRequest("POST", gw.URL+"/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+secrets[0]) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { res.Body.Close() }) + return res + } + first := post("first") + if line, _ := bufio.NewReader(first.Body).ReadString('\n'); !strings.Contains(line, "from first") { + t.Fatalf("first = %q", line) + } + // the second has its headers while it waits, nothing sent upstream + second := post("second") + if second.StatusCode != 200 || !strings.Contains(second.Header.Get("Content-Type"), "event-stream") { + t.Fatalf("waiting stream: %d %s", second.StatusCode, second.Header.Get("Content-Type")) + } + if slices.Contains(v.seen(), "second") { + t.Fatal("second reached the vendor with first out") + } + close(v.gate("first")) + close(v.gate("second")) + b, _ := io.ReadAll(second.Body) + if !strings.Contains(string(b), "from second") || !strings.Contains(string(b), "[DONE]") { + t.Fatalf("second's stream = %.300s", b) + } +} + +// The routes that wait before their handler (keySlotEager) hold a key to +// its cap as well: with 1, the second waits for the first's handler to +// return, one gone while waiting never runs, and a key issued under it +// waits for a slot of its issuer's too. +func TestKeyConcurrencyEager(t *testing.T) { + fresh(t) + var in, most atomic.Int32 + var mu sync.Mutex + ran := []string{} + gates := map[string]chan struct{}{} + gate := func(tag string) chan struct{} { + mu.Lock() + defer mu.Unlock() + if gates[tag] == nil { + gates[tag] = make(chan struct{}) + } + return gates[tag] + } + mux := &routeMux{ServeMux: http.NewServeMux()} + mux.HandleFunc("POST /v1/embeddings", func(w http.ResponseWriter, r *http.Request) { + n := in.Add(1) + defer in.Add(-1) + for m := most.Load(); n > m && !most.CompareAndSwap(m, n); m = most.Load() { + } + tag := r.URL.Query().Get("t") + mu.Lock() + ran = append(ran, tag) + mu.Unlock() + <-gate(tag) + }) + s := New() + h := s.keySlots(mux, mux) + parent := access.Identity{KeyID: "p", KeyName: "Parent", MaxConcurrency: 1} + child := access.Identity{KeyID: "c", KeyName: "Child", Issuer: &parent} + done := make(chan string, 8) + send := func(ctx context.Context, who access.Identity, tag string) { + go func() { + r := httptest.NewRequestWithContext(access.WithIdentity(ctx, who), "POST", "/v1/embeddings?t="+tag, strings.NewReader("{}")) + h.ServeHTTP(httptest.NewRecorder(), r) + done <- tag + }() + } + seen := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(ran) } + send(context.Background(), parent, "one") + within(t, "one runs", func() bool { return len(seen()) == 1 }) + send(context.Background(), child, "issued") + within(t, "the issued key's waits for its issuer's slot", func() bool { return s.KeyLanes()["p"].Waiting == 1 }) + ctx, cancel := context.WithCancel(context.Background()) + send(ctx, parent, "gone") + within(t, "gone queued", func() bool { return s.KeyLanes()["p"].Waiting == 2 }) + cancel() + if tag := <-done; tag != "gone" { + t.Fatalf("%s returned first", tag) + } + close(gate("one")) + within(t, "the issued key's runs", func() bool { return slices.Contains(seen(), "issued") }) + close(gate("issued")) + <-done + <-done + if got := seen(); !slices.Equal(got, []string{"one", "issued"}) || most.Load() != 1 { + t.Fatalf("ran %v, %d at once", got, most.Load()) + } + within(t, "every key slot given back", func() bool { return len(s.KeyLanes()) == 0 }) + // a GET, or a key with no cap, is never held + r := httptest.NewRequest("GET", "/v1/embeddings", nil) + h.ServeHTTP(httptest.NewRecorder(), r.WithContext(access.WithIdentity(r.Context(), access.Identity{KeyID: "p", MaxConcurrency: 1}))) + if len(s.KeyLanes()) != 0 { + t.Fatal("a GET took a slot") + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 8173a16a5..47e8807a2 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3020,10 +3020,14 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* the models a key may use (#882): a long model's id is cut, and the badge gives way first on a narrow window */ #gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } -/* a key's quotas badge (#2216) takes no room until the row is hovered, - and gives way before the row runs past a narrow window */ -#gatewayKeys .amodels.key-quotas { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } -#gatewayKeys .acc:not(:hover) > .key-quotas:not(.set):not(:focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } +/* a key's quotas and concurrency badges (#2216) take no room until the + row is hovered, and give way before the row runs past a narrow window */ +#gatewayKeys .amodels:is(.key-quotas, .key-conc) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } +/* unset, shown by a hover, they give way before the masked key does: the + key squeezed by them on a narrow window slid its copy button under the + pointer that came to drag the row */ +#gatewayKeys .acc > :is(.key-quotas, .key-conc):not(.set) { flex-shrink: 8; } +#gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } /* the MCP servers a key held to some may use: cut, and gives way first */ #gatewayKeys .amodels.key-mcp { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* a read-only key's tag, always shown, never a button */ @@ -4322,8 +4326,8 @@ body.panel .modal { padding: 16px 12px; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal):not(.set) { margin-left: 0 !important; } body.web .accts.keys .acc > .abal.abal-many { flex-shrink: 1 !important; padding-block: 2px !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } - body.web #gatewayKeys .acc > .key-quotas { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } - body.web #gatewayKeys .acc > .key-quotas:not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } } /* Import from other apps: a checklist per app */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c862893d7..fb1659307 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2575,6 +2575,8 @@ const I18N = { "the provider's": "沿用提供商设置", "At most {n} requests out at once on this one, {whose}; more wait in a queue and go in order. Counted across every model, routing group and agent": "此项最多同时 {n} 个请求({whose}),多出的按顺序排队。所有模型、路由组和客户端共用此计数", "No limit on requests at once on this one, {whose}": "此项同时请求数不限({whose})", + "At most {n} requests of this key at once; more wait in a queue and go in order": "这个密钥最多同时 {n} 个请求,多出的排队依次发出", + "No limit on this key's requests at once": "这个密钥的同时请求数不限", "{n} running, {q} queued now": "当前 {n} 个运行中,{q} 个排队", "Click to change": "点击修改", "{who} takes the provider's limit": "{who} 改为沿用提供商的并发上限", @@ -7305,6 +7307,8 @@ const I18N = { "the provider's": "沿用提供商設定", "At most {n} requests out at once on this one, {whose}; more wait in a queue and go in order. Counted across every model, routing group and agent": "此項最多同時 {n} 個請求({whose}),多出的按順序排隊。所有模型、路由組和用戶端共用此計數", "No limit on requests at once on this one, {whose}": "此項同時請求數不限({whose})", + "At most {n} requests of this key at once; more wait in a queue and go in order": "這個金鑰最多同時 {n} 個請求,多出的排隊依序送出", + "No limit on this key's requests at once": "這個金鑰的同時請求數不限", "{n} running, {q} queued now": "目前 {n} 個執行中,{q} 個排隊", "Click to change": "點選修改", "{who} takes the provider's limit": "{who} 改為沿用提供商的並行上限", @@ -12013,6 +12017,8 @@ const I18N = { "the provider's": "プロバイダーの設定", "At most {n} requests out at once on this one, {whose}; more wait in a queue and go in order. Counted across every model, routing group and agent": "この項目で同時に送るリクエストは最大 {n} 件({whose})。超えた分は順番に待ちます。すべてのモデル・ルーティンググループ・エージェントで共有されます", "No limit on requests at once on this one, {whose}": "この項目の同時リクエスト数は無制限({whose})", + "At most {n} requests of this key at once; more wait in a queue and go in order": "このキーの同時リクエストは最大 {n} 件。超えた分は順番待ちで順に送られます", + "No limit on this key's requests at once": "このキーの同時リクエスト数は無制限", "{n} running, {q} queued now": "現在 {n} 件実行中、{q} 件待ち", "Click to change": "クリックで変更", "{who} takes the provider's limit": "{who} はプロバイダーの同時数上限に従います", @@ -16752,6 +16758,8 @@ const I18N = { "the provider's": "die des Anbieters", "At most {n} requests out at once on this one, {whose}; more wait in a queue and go in order. Counted across every model, routing group and agent": "Höchstens {n} Anfragen gleichzeitig hierüber ({whose}); weitere warten der Reihe nach. Gezählt über alle Modelle, Routing-Gruppen und Agenten", "No limit on requests at once on this one, {whose}": "Keine Grenze für gleichzeitige Anfragen hierüber ({whose})", + "At most {n} requests of this key at once; more wait in a queue and go in order": "Höchstens {n} Anfragen dieses Schlüssels gleichzeitig; weitere warten in einer Schlange und gehen der Reihe nach", + "No limit on this key's requests at once": "Keine Grenze für gleichzeitige Anfragen dieses Schlüssels", "{n} running, {q} queued now": "Jetzt {n} laufen, {q} warten", "Click to change": "Klicken zum Ändern", "{who} takes the provider's limit": "{who} übernimmt die Grenze des Anbieters", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 3780f9faa..f2a7a45af 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -226,7 +226,7 @@ function renderGatewayKeys() { tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }); // the copy sits by the key it copies (the owner: stranded among the // badges it read as nobody's); Rotate and Remove wait in the row's menu - row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), gatewayKeyMore(k)); + row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u)); if (under.length) row.classList.add("with-limit"), row.append(...under); list.append(row); @@ -618,6 +618,58 @@ function gatewayQuotasBadge(k) { return b; } +// a key's requests at once (young02036 on Discord), as an account's are +// set on the Providers page: the app's menu, no limit, a number, or the +// user's own; more wait in a queue and go in order +const KEY_CONC = [1, 2, 3, 5, 10]; +function gatewayConcurrencyBadge(k) { + const own = k.maxConcurrency || 0; + const b = el("button", "amodels key-conc" + (own ? " set" : "")); + b.type = "button"; + b.textContent = own ? t("{n} at once", { n: own }) : t("No limit at once"); + b.title = own ? t("At most {n} requests of this key at once; more wait in a queue and go in order", { n: own }) : t("No limit on this key's requests at once"); + b.setAttribute("aria-label", t("Requests at once")); + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-expanded", "false"); + const set = async (v) => { + const out = await gatewayKeyAction("concurrency-key", { key: k.id, maxConcurrency: v }); + if (out) status(v ? t("{who}: at most {n} requests at once", { who: k.name, n: v }) : t("{who}: no limit on requests at once", { who: k.name }), "ok"); + }; + // Other…: a number of the user's own, in the badge's place + const other = () => { + const i = input(own ? String(own) : "", "1–1000", "text"); + i.className = "rename-in alane-in"; + i.inputMode = "numeric"; + i.setAttribute("aria-label", t("Requests at once")); + let done = false; + const finish = (save) => { + if (done) return; + done = true; + const s = i.value.trim(); + const v = /^\d+$/.test(s) && +s <= 1000 ? +s : null; + if (save && s && v == null) { status(t("Concurrency: a whole number from 0 to 1000"), "err"); return renderGatewayKeys(); } + if (save && s && v !== own) set(v); + else renderGatewayKeys(); + }; + i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") finish(true); else if (e.key === "Escape") finish(false); }; + i.onblur = () => finish(true); + b.replaceWith(i); + i.focus({ preventScroll: true }); + }; + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + const nums = !own || KEY_CONC.includes(own) ? KEY_CONC : [...KEY_CONC, own].sort((x, y) => x - y); + const opts = [{ v: 0, name: "No limit", note: "Any number at once" }, ...nums.map((n) => ({ v: n, name: String(n), note: "", literalName: true })), + { v: -1, name: "Other…", note: "A number of your own, up to 1000" }]; + openProtoMenu(b, opts, own, (v) => { + if (v === -1) return other(); + if (v !== own) set(v); + }, "Requests at once", "sess-menu"); + }; + return b; +} + // ---- a gateway key's own limit (#585) ---- // "days" is every N days from when the limit is set or reset (#1509), diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 67ddf4792..ea824b8b5 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -193,6 +193,11 @@ function fixture(lang, theme, events, options = {}) { if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined; if (action === "mcp-key") k.mcp = body.mcp?.length ? body.mcp : undefined; if (action === "quotas-key") k.quotas = body.quotas || undefined; + // as access.Update: a whole number from 0 (no limit) to 1000 + if (action === "concurrency-key") { + if (!Number.isInteger(body.maxConcurrency) || body.maxConcurrency < 0 || body.maxConcurrency > 1000) return route.fulfill({ status: 400, json: { error: "Concurrency: a whole number from 0 to 1000" } }); + k.maxConcurrency = body.maxConcurrency || undefined; + } if (action === "access-key") k.readOnly = body.readOnly || undefined; // a key put at a place in the list, as access.Update keeps it; // options.refuseMove: the store can't be written diff --git a/internal/gui/tests/gateway-key-concurrency.test.cjs b/internal/gui/tests/gateway-key-concurrency.test.cjs new file mode 100644 index 000000000..2e24d1791 --- /dev/null +++ b/internal/gui/tests/gateway-key-concurrency.test.cjs @@ -0,0 +1,100 @@ +// A gateway key's requests at once (young02036 on Discord), set as an +// account's are on the Providers page: a badge on the key's row, shown +// always while set and on hover while not, opens the app's menu (no +// native select): no limit, a number, or Other… typed in place. It sends +// "concurrency-key"; a value that isn't a whole number up to 1000 is +// refused and sends nothing. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const words = { + en: { label: "Requests at once", none: "No limit", off: "No limit at once", at: (n) => `${n} at once`, other: "Other…" }, + zh: { label: "同时请求数", none: "不限制", off: "并发不限", at: (n) => `并发 ${n}`, other: "其他…" }, + "zh-TW": { label: "同時請求數", none: "不限制", off: "並行不限", at: (n) => `並行 ${n}`, other: "其他…" }, + ja: { label: "同時リクエスト数", none: "上限なし", off: "同時数 無制限", at: (n) => `同時 ${n}`, other: "その他…" }, + de: { label: "Gleichzeitige Anfragen", none: "Kein Limit", off: "Gleichzeitig unbegrenzt", at: (n) => `${n} gleichzeitig`, other: "Andere…" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width} ${lang}: a key's requests at once are set from the app's menu`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { maxConcurrency: 3 }, laptop: { readOnly: true } } })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const badge = (id) => row(id).locator(".key-conc"); + const item = (name) => page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) }) }); + const sent = () => events.filter((e) => e.action === "concurrency-key").map((e) => e.body); + const reads = async (id, text) => page.waitForFunction(([id, text]) => document.querySelector(`#gatewayKeys .acc[data-key="${id}"] .key-conc`)?.textContent === text, [id, text]); + const view = page.locator("#view-gateway"); + const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)]; + const before = await scrolled(); + + // set: said always, not only on hover; a read-only key has none + await page.mouse.move(0, 0); + assert.equal(await badge("server").textContent(), w.at(3)); + assert.equal(await badge("server").evaluate((b) => getComputedStyle(b).opacity), "1"); + assert.equal(await badge("server").getAttribute("aria-label"), w.label); + assert.equal(await badge("laptop").count(), 0, "a read-only key uses no model"); + // unset: on hover only + assert.equal(await badge("work").evaluate((b) => getComputedStyle(b).opacity), "0"); + await row("work").hover(); + assert.equal(await badge("work").textContent(), w.off); + + // a number from the menu + await badge("work").click(); + await page.locator(".proto-menu").waitFor(); + assert.equal(await page.locator(".proto-menu .pm-head").textContent(), w.label); + await item("2").click(); + await reads("work", w.at(2)); + assert.deepEqual(sent(), [{ key: "work", maxConcurrency: 2 }]); + + // Other…: a bad value is refused and sends nothing, a good one is kept + await row("server").hover(); + await badge("server").click(); + await item(w.other).click(); + let box = row("server").locator("input.alane-in"); + await box.fill("2000"); + await box.press("Enter"); + await reads("server", w.at(3)); + assert.equal(sent().length, 1, "a value over 1000 was sent"); + await row("server").hover(); + await badge("server").click(); + await item(w.other).click(); + box = row("server").locator("input.alane-in"); + await box.fill("7"); + await box.press("Enter"); + await reads("server", w.at(7)); + assert.deepEqual(sent().at(-1), { key: "server", maxConcurrency: 7 }); + // 7 is offered in the menu now, and No limit turns it off + await row("server").hover(); + await badge("server").click(); + assert.equal(await item("7").count(), 1); + await item(w.none).click(); + await reads("server", w.off); + assert.deepEqual(sent().at(-1), { key: "server", maxConcurrency: 0 }); + + assert.deepEqual(await scrolled(), before, "a click moved the page"); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + await row("work").hover(); + const rowBox = await row("work").boundingBox(), b = await badge("work").boundingBox(); + assert.ok(b.x >= rowBox.x && b.x + b.width <= rowBox.x + rowBox.width + 1, "the badge runs out of its row"); + assert.equal(await page.locator("select").count(), 0, "no native select"); + const lefts = await page.locator("#gatewayKeys .key-conc").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle)); + assert(lefts.every((s) => s === "none"), "a coloured left border"); + assert.deepEqual(errors, []); + }); + } + } +}