Files
magpie/internal/provider/concurrency.go
T
yetone 39af4adda5 gateway, gui, cli: each account or key can have its own limit on requests at once, with a bounded queue that turns requests away with a 429 (#892, margbug01) — a provider's Concurrency applied to every key and account alike, the queue past it had no bound and no wait, and nothing showed what ran or waited. A key or account now may have its own limit over the provider's (Provider.AccountConcurrency, by lowercased account or KeyID; 0 none; unset takes the provider's, as before), counted in one lane across every model, routing group and agent. A provider's Queue size bounds how many wait for each of its lanes (one more is turned away at once) and Queue wait how many seconds one waits (then it leaves the queue); both 0 by default, as before. A request turned away goes on to the next key, account or group member without resting anything, else gets a 429 in its API's own shape (Anthropic rate_limit_error, OpenAI's, Gemini's) with Retry-After: 1, saying the limit and the queue. A slot is given back when the reply is read to the end, fails or the agent goes away; a waiter that goes away leaves the queue, and one granted as it gave up hands the slot on. In a routing group, or among a provider's keys and accounts, a full one gives way once to another with a free slot now, so a group spreads before anyone waits; a fallback provider is never asked for want of a slot, and with all full the request waits for the one routing chose. The Claude subscription path and plugin providers take their slot the same way, around the attempt; a parked Claude Code tool turn has already answered and holds none. GUI: each account and key row has a pill — "1/1 running · 2 queued" while requests are out (GET /api/lanes, read every two seconds and written into the pill in place), else its limit; none set shows on hover only — opening the app's menu (provider's, no limit, 1/2/3/5/10, Other… typed in place), posting provider/accountconcurrency; the editor has Queue size and Queue wait under Concurrency. CLI: magpie provider account-concurrency <id> [account|key [n|off|default]] and magpie provider queue <id> [size [seconds]]. en/zh/ja/de. TestAccountLimitSharedAcrossGroups, TestQueueFullAndWaitedOut, TestLaneReleasedOnFailure and TestFullMemberGivesWay (pass with -race, with TestMaxConcurrency and TestLanesLimitLifted), TestLaneLimitRoutes and TestAccountConcurrencyCmd are new and fail without the change; lane-limit.test.cjs (WebKit, en and zh: a key's busy/queued pill updated in place from /api/lanes, set from the menu, provider's posts null, Other… typed, an account's own limit, none on hover only, queue fields saved and refused out of range, labels on one line, every string in zh/ja/de, no select, no scroll, no left border) fails without the change. key-weight-fit, account-cap, provider-concurrency, click-scroll, account-models and api-key-usage pass in WebKit; the other WebKit failures fail the same on main. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-05 18:53:16 +08:00

182 lines
5.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package provider
import (
"fmt"
"strconv"
"strings"
)
// Concurrency is how many requests the gateway lets be out at the vendor
// at once on each of the provider's keys or accounts, 0 for no limit: the
// user's MaxConcurrency when they set one, else what the plugin giving the
// provider says it takes (its auth hook's maxConcurrency, or its
// package.json's magpie.maxConcurrency), else none.
func (p Provider) Concurrency() int {
if p.MaxConcurrency != nil {
return max(*p.MaxConcurrency, 0)
}
return p.PluginConcurrency()
}
// PluginConcurrency is what the plugin giving the provider says it takes
// at once, as it lists it now; 0 for none, or for a provider no plugin
// gives.
func (p Provider) PluginConcurrency() int {
if !p.IsPlugin() {
return 0
}
if cur, ok := PluginOf(p.ID); ok {
return max(cur.MaxConcurrency, 0)
}
return max(p.Account.plugin.MaxConcurrency, 0)
}
// One account's or key's own limit (#892: a Claude account kept to two
// at once while the provider's others take more), the queue's bound and
// how long a request waits in it. The limit is the lane's — the account
// or key itself — so whatever asks for it, a model, a routing group or an
// agent, counts against the one number (gateway/concurrency.go).
// MaxLimit bounds a limit on requests at once; MaxQueueLimit how many
// may wait, MaxQueueWait how long one waits, in seconds.
const (
MaxLimit = 1000
MaxQueueLimit = 10000
MaxQueueWait = 3600
)
// LaneLimit is how many requests may be out at once on p's key or
// account, 0 for no limit: its own (AccountConcurrency), else the
// provider's (Concurrency). An account made afresh beside the agent's own
// (AlsoOn) carries none of the provider's settings: they are read from
// providers.json then.
func (p Provider) LaneLimit() int {
ref := ""
switch {
case p.Account != nil:
ref = p.Account.User
case p.Key != "":
ref = KeyID(p.Key)
}
if ref == "" {
return p.Concurrency()
}
m := p.AccountConcurrency
if m == nil && p.Account != nil {
if s, ok := storedPicks(p.ID); ok {
m = s.AccountConcurrency
}
}
if n, ok := m[accountKey(ref)]; ok {
return max(n, 0)
}
return p.Concurrency()
}
// AccountConcurrencyOf is the account's or key's own limit, and whether it
// has one (else it takes the provider's).
func (p Provider) AccountConcurrencyOf(ref string) (int, bool) {
n, ok := p.AccountConcurrency[accountKey(ref)]
return n, ok
}
// AccountRefOf is the account or key of p that ref names, as its limit is
// kept: an account's name, a key's KeyID (by its id or name).
func (p Provider) AccountRefOf(ref string) (string, bool) {
return p.accountRef(ref)
}
// SetAccountConcurrency gives the account or key ref of the provider id
// its own limit on requests at once, 0 for none; nil gives it the
// provider's again.
func SetAccountConcurrency(id, ref string, limit *int) error {
if limit != nil && (*limit < 0 || *limit > MaxLimit) {
return fmt.Errorf("a limit on requests at once is from 0 (none) to %d, not %d", MaxLimit, *limit)
}
p, err := Find(id)
if err != nil {
return err
}
r, ok := p.accountRef(ref)
if !ok {
if p.Account == nil {
return fmt.Errorf("%s has no key %q", p.Name, ref)
}
return fmt.Errorf("%s has no account %q", p.Name, ref)
}
m := map[string]int{}
for k, v := range p.AccountConcurrency {
m[k] = v
}
if limit == nil {
if _, had := m[accountKey(r)]; !had {
return nil
}
delete(m, accountKey(r))
} else {
m[accountKey(r)] = *limit
}
p.AccountConcurrency = m
return Save(*p)
}
// CheckQueue says what is wrong with a queue's bound or wait, nil when
// nothing is.
func CheckQueue(limit, wait int) error {
if limit < 0 || limit > MaxQueueLimit {
return fmt.Errorf("a queue holds from 0 (no bound) to %d requests, not %d", MaxQueueLimit, limit)
}
if wait < 0 || wait > MaxQueueWait {
return fmt.Errorf("a request waits from 0 (as long as it takes) to %d seconds, not %d", MaxQueueWait, wait)
}
return nil
}
// SetQueue sets how many requests may wait for each of the provider's keys
// or accounts, and how long one waits, in seconds; 0 is no bound.
func SetQueue(id string, limit, wait int) error {
if err := CheckQueue(limit, wait); err != nil {
return err
}
p, err := Find(id)
if err != nil {
return err
}
p.QueueLimit, p.QueueWait = limit, wait
return Save(*p)
}
// ParseLimit reads a limit as the CLI takes it: a whole number, 0 or off
// for no limit, default for the provider's (nil).
func ParseLimit(s string) (*int, error) {
s = strings.ToLower(strings.TrimSpace(s))
switch s {
case "default", "provider", "inherit":
return nil, nil
case "off", "none", "no", "-", "unlimited":
return new(int), nil
}
n, err := strconv.Atoi(s)
if err != nil || n < 0 || n > MaxLimit {
return nil, fmt.Errorf("a limit is a whole number from 0 (none) to %d, off, or default, not %q", MaxLimit, s)
}
return &n, nil
}
// normalAccountConcurrency is m as it is kept: keys in lower case, limits
// within 0–MaxLimit; nil for none.
func normalAccountConcurrency(m map[string]int) map[string]int {
var out map[string]int
for u, n := range m {
u = accountKey(u)
if u == "" {
continue
}
if out == nil {
out = map[string]int{}
}
out[u] = min(max(n, 0), MaxLimit)
}
return out
}