From f299faef487384e7bb7fd72216d054152a61ec54 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 01:46:14 +0800 Subject: [PATCH] gateway keys: a key holds several limits at once, every one must pass, and the 429 names the one that resets last (#2227, oxsean) A key may now hold up to five limits, each in its own window (5 hours and a week, say). A request needs every one: budget.Reserve checks each, holds one reservation per window and settles each, and when some are spent refuses with the spent limit that resets last, so X-Magpie-Limit-Reset and Retry-After say when the key is really back. Two limits in one window are refused (change that one instead). Saved format: the first limit stays in "limit", which older magpie reads, the rest go in "moreLimits". A file without moreLimits reads as before. - access: Change.Index adds (index = len), replaces (keeps its Since) or removes (nil) one limit; reset-limit-key with an index resets one, without resets all; the plain limit-key replaces all, as before. - /v1/magpie/limit: "limit" is the binding one (what older clients read), "limits" is each. A remote key card shows a window per cap of each limit and falls back to "limit" from an older remote. - CLI: magpie gateway-key limit list | add ... | remove | reset []; the single-limit form still replaces all. - GUI: the key's badge names the limit holding it most and "+N limit(s)", a line per limit under the row, and the editor has a tab per limit with Add a limit / Remove this limit. Strings in en, zh, zh-TW, ja, de. - docs/reference.md and docs/subsystems/gateway-routing.md say so. Run (worktree on e98440ae6, sandbox HOME): - go test ./internal/access/ ./internal/budget/ ./internal/gateway/ ./internal/cli/ ./internal/provider/ ./internal/gui/: all ok. - gofmt -l clean; go vet darwin, GOOS=linux -tags=nogui, GOOS=windows on those packages: clean. - GUI (Playwright 1.62.0) chromium and webkit: the new gateway-key-limits test (5 languages x 1100/420), gateway-key*, gateway-caller-keys, gateway-keys-off, gateway-own-key, gateway-connect-keys: 94/94; i18n-keys ok. quota-name-translated webkit en is red with HEAD's assets too, filed as #2228. - Broken by hand, each went red: Reserve checking the first limit only; the refusal naming the first spent limit, not the latest reset; the endpoint without "limits"; every limit saved in moreLimits; duplicate windows allowed; the remote card ignoring "limits"; the CLI plain form adding instead of replacing; the GUI save without its index; the GUI badge taking the first limit. Not tried: against a real remote magpie or real accounts. Known gaps: two N-day cycle limits are both named "this cycle" on a remote card; an older magpie that rewrites the keys file keeps only the first limit. --- docs/reference.md | 22 +- docs/subsystems/gateway-routing.md | 12 +- internal/access/access.go | 76 +++- internal/access/limit.go | 54 +++ internal/access/limit_test.go | 117 +++++++ internal/budget/budget.go | 233 +++++++++--- internal/cli/gateway_keys_cli.go | 331 ++++++++++++------ internal/cli/gateway_keys_cli_test.go | 81 +++++ internal/cli/main.go | 2 +- internal/gateway/key_limit.go | 17 +- internal/gateway/key_limit_test.go | 83 +++++ internal/gateway/remote_key_limits_test.go | 11 + internal/gateway/usage_api.go | 2 +- internal/gui/assets/app.css | 5 + internal/gui/assets/i18n.js | 28 ++ internal/gui/assets/plugins/gateway/keys.js | 107 ++++-- internal/gui/caller_keys.go | 12 +- internal/gui/tests/fixtures/caller-keys.cjs | 31 +- .../gui/tests/gateway-key-limits.test.cjs | 143 ++++++++ internal/provider/remote_key_limits.go | 66 ++-- internal/provider/remote_key_limits_test.go | 19 + 21 files changed, 1194 insertions(+), 258 deletions(-) create mode 100644 internal/gui/tests/gateway-key-limits.test.cjs create mode 100644 internal/provider/remote_key_limits_test.go diff --git a/docs/reference.md b/docs/reference.md index a921b7f7b..7992d6291 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -503,10 +503,12 @@ magpie gateway-key list # ids, names, enabled state and masked ke magpie gateway-key rotate # prints the replacement; identity stays the same magpie gateway-key remove # revokes remote access magpie gateway-key limit week --tokens 2m --cost 5 # its own limit -magpie gateway-key limit # limit, used, left and reset +magpie gateway-key limit list # each limit, used, left and reset magpie gateway-key limit 10d --tokens 5m # every 10 days, from now magpie gateway-key limit 5h --tokens 200k # every 5 hours, from now -magpie gateway-key limit reset # count its usage from 0 again +magpie gateway-key limit add week --cost 20 # one more limit; all must pass +magpie gateway-key limit remove 2 # take off the 2nd limit +magpie gateway-key limit reset # count its usage from 0 again (reset 2: only the 2nd) magpie gateway-key limit off # no limit magpie gateway-key models openai/gpt-5 anthropic/* # only these models magpie gateway-key models all # every model @@ -525,7 +527,17 @@ move it. Changing only the caps or **Count cache reads too** keeps the cycle; changing N or the period, or turning the limit on, starts a new one then. Set it with **Limit** on the key's row (saved with Save) or `magpie gateway-key limit`; the row shows -what the key has used, what is left and when it resets. Tokens counted are a +what the key has used, what is left and when it resets. A key can have up to +five limits, each in a window of its own (#2227), such as $3 every 5 hours and +$20 a week, as a subscription's two windows: **Add a limit** in the editor or +`magpie gateway-key limit add`. A request passes only while every one has +something left; its reservation is held in each window, and its 429 names the +spent limit that resets last. Two limits can't share a window: a window's +tokens and cost caps go in one limit. Setting a window without `add` changes +the key's limit of that window, or its only one. `GET /v1/magpie/limit` gives +each in `limits`, and in `limit` the one holding the key most, which a magpie +from before #2227 reads; such a magpie also keeps only the first limit +(`limit` in caller-keys.json, the rest under `moreLimits`). Tokens counted are a call's uncached input, output and cache writes, plus cache reads when **Count cache reads too** is on. Cost is an estimate at the Usage page's prices; a call with no known price adds none. A call counts in the window it started @@ -537,7 +549,9 @@ flight holds a reservation (its body's size in tokens plus the key's mean output per call), so requests sent at once overshoot by about one call; a streamed reply is settled when it ends with the usage its vendor reported. **Reset usage** in the key's limit editor (or `magpie gateway-key limit - reset`) counts the key's tokens and cost from 0 together, from now. An + reset`) counts the key's tokens and cost from 0 together, from now: the +editor's resets the limit it is open on, the CLI's every limit, or the nth +with `reset `. An N-day or N-hour key starts a new cycle then. A day, week or month key keeps its window's end (midnight, Monday, the 1st): only the calls before the reset stop counting, so it doesn't drift off the calendar. The reset is diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index cd9195f11..7949a6a68 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -159,9 +159,15 @@ are described in [Providers and accounts](providers-accounts.md#remote-magpie). `GET /v1/magpie/limit` (`keyLimit` in [`key_limit.go`](../../internal/gateway/key_limit.go)) answers the limit of the gateway key the request carries (`access.Caller`) and of no other: it -reads nothing from the request but its key. A local magpie asks it with -each of its remote-magpie keys for that key's card on its Usage page -(#1547). +reads nothing from the request but its key. A key may hold up to five +limits at once, each in its own window, and a request needs every one +(#2227, `budget.Reserve`: one reservation per window, and a refusal names +the spent limit that resets last). The saved key keeps the first limit in +`limit`, which older magpie reads, and the rest in `moreLimits`. The answer's +`limit` is the one holding the key most (`budget.Binding`), what older +clients read, and `limits` is each of them (`budget.All`). A local magpie +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. System One uses `RouteDecider` and `postDecide` in [`decide.go`](../../internal/gateway/decide.go), taking one provider prefix diff --git a/internal/access/access.go b/internal/access/access.go index e47805cfe..cb01a660d 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -117,6 +117,10 @@ type Key struct { Masked string `json:"masked,omitempty"` // Limit is the key's own budget (#585); nil for none. Limit *Limit `json:"limit,omitempty"` + // More are its limits after the first (#2227), each a window of its + // own: a request passes only while every one has something left. A + // key has them only beside a Limit, which an older magpie still reads. + More []Limit `json:"moreLimits,omitempty"` // Models are the models the key may use (#882): "/", // "/*" or a group's "group/"; none for every model. Models []string `json:"models,omitempty"` @@ -131,6 +135,7 @@ type Key struct { type Identity struct { KeyID, KeyName string Limit *Limit + More []Limit Models []string Accounts []string } @@ -244,6 +249,12 @@ type Change struct { Name string `json:"name"` // Limit is what "limit-key" sets; nil or Unlimited takes the limit off. Limit *Limit `json:"limit,omitempty"` + // Index is which of the key's limits "limit-key" sets and + // "reset-limit-key" resets (#2227), counted from 0: one past the last + // adds a limit, a nil Limit there removes that one. Without it, + // "limit-key" makes Limit the key's only limit, and "reset-limit-key" + // resets every one. + Index *int `json:"index,omitempty"` // Models is what "models-key" sets; none lets the key use every model. Models []string `json:"models,omitempty"` // Accounts is what "accounts-key" sets (#905); none lets the key use @@ -315,20 +326,67 @@ func Update(action string, in Change) (string, error) { if err != nil { return "", err } - if lim != nil { - lim.Since = sinceOf(keys[i].Limit, lim, Now().Round(0)) + ls := keys[i].limitList() + now := Now().Round(0) + if in.Index == nil { + var first *Limit + if len(ls) > 0 { + first = &ls[0] + } + ls = nil + if lim != nil { + lim.Since = sinceOf(first, lim, now) + ls = []Limit{*lim} + } + } else { + n := *in.Index + if n < 0 || n > len(ls) || (n == len(ls) && lim == nil) { + return "", errors.New("This key has no such limit") + } + switch { + case lim == nil: + ls = slices.Delete(ls, n, n+1) + case n == len(ls): + if len(ls) >= MaxLimits { + return "", fmt.Errorf("A key can have at most %d limits", MaxLimits) + } + lim.Since = sinceOf(nil, lim, now) + ls = append(ls, *lim) + default: + lim.Since = sinceOf(&ls[n], lim, now) + ls[n] = *lim + } } - keys[i].Limit = lim + for a := range ls { + for b := a + 1; b < len(ls); b++ { + if ls[a].sameWindow(&ls[b]) { + return "", fmt.Errorf("This key already has a limit %s: change that one instead", ls[a].Per()) + } + } + } + keys[i].setLimits(ls) case "reset-limit-key": // what the key has used is counted again from now (#1509), // its tokens and cost together: a "days" or "hours" cycle starts anew, - // a calendar window keeps its end - if !keys[i].Limit.Limited() { + // a calendar window keeps its end; one limit of several, or + // every one (#2227) + ls := keys[i].limitList() + if len(ls) == 0 { return "", errors.New("This key has no limit to reset") } - l := *keys[i].Limit - l.Since = Now().Round(0) - keys[i].Limit = &l + now := Now().Round(0) + if in.Index != nil { + n := *in.Index + if n < 0 || n >= len(ls) { + return "", errors.New("This key has no such limit") + } + ls[n].Since = now + } else { + for j := range ls { + ls[j].Since = now + } + } + keys[i].setLimits(ls) case "models-key": ms, err := CleanModels(in.Models) if err != nil { @@ -402,7 +460,7 @@ func Authenticate(secret string) (Identity, bool) { if k.Off { return Identity{}, false } - return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, Models: k.Models, Accounts: k.Accounts}, true + return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: k.Models, Accounts: k.Accounts}, true } } s := settings.Load() diff --git a/internal/access/limit.go b/internal/access/limit.go index ff86c739b..95ae12e44 100644 --- a/internal/access/limit.go +++ b/internal/access/limit.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "math" + "slices" "time" ) @@ -34,6 +35,59 @@ type Limit struct { Since time.Time `json:"since,omitzero"` } +// MaxLimits is how many limits one key can have (#2227). +const MaxLimits = 5 + +// Limits are k's limits, its Limit first; none for a key with no limit. +// Each holds the key on its own: a request passes only while all of them +// have something left. +func (k Key) Limits() []*Limit { return limitsOf(k.Limit, k.More) } + +// Limits are the limits who's key holds it to, as Key.Limits. +func (who Identity) Limits() []*Limit { return limitsOf(who.Limit, who.More) } + +func limitsOf(first *Limit, more []Limit) []*Limit { + var out []*Limit + if first.Limited() { + out = append(out, first) + } + for i := range more { + if more[i].Limited() { + out = append(out, &more[i]) + } + } + return out +} + +// limitList is a copy of k's limits, to change and set back. +func (k *Key) limitList() []Limit { + var out []Limit + for _, l := range k.Limits() { + out = append(out, *l) + } + return out +} + +// setLimits keeps ls as k's limits: the first as Limit, so a magpie from +// before #2227 still holds the key to it, the rest as More. +func (k *Key) setLimits(ls []Limit) { + k.Limit, k.More = nil, nil + if len(ls) > 0 { + first := ls[0] + k.Limit = &first + k.More = slices.Clone(ls[1:]) + } + if len(k.More) == 0 { + k.More = nil + } +} + +// sameWindow: l and o count in the same window, so two limits of one key +// that do are one limit with two caps. +func (l *Limit) sameWindow(o *Limit) bool { + return l.Period == o.Period && l.Days == o.Days && l.Hours == o.Hours +} + // Periods are the windows a limit can be set for. var Periods = []string{"day", "week", "month", "days", "hours"} diff --git a/internal/access/limit_test.go b/internal/access/limit_test.go index 64d5689da..7987997fe 100644 --- a/internal/access/limit_test.go +++ b/internal/access/limit_test.go @@ -1,6 +1,7 @@ package access import ( + "encoding/json" "os" "strings" "testing" @@ -343,3 +344,119 @@ func TestLimitHoursSetAndReset(t *testing.T) { t.Fatalf("after reset: %s – %s", start, reset) } } + +// A key holds several limits at once (#2227): the first stays where an +// older magpie reads it, the rest go beside it, and each is added, +// changed, removed and reset on its own. +func TestSeveralLimits(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clock := time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC) + Now = func() time.Time { return clock } + t.Cleanup(func() { Now = time.Now }) + secret, err := Update("add-key", Change{Name: "Shared"}) + if err != nil { + t.Fatal(err) + } + keys, _ := List() + id := keys[0].ID + at := func(n int, l *Limit) error { + _, err := Update("limit-key", Change{Key: id, Limit: l, Index: &n}) + return err + } + limits := func() []*Limit { + t.Helper() + keys, err := List() + if err != nil || len(keys) != 1 { + t.Fatal(keys, err) + } + return keys[0].Limits() + } + if err := at(0, &Limit{Period: "hours", Hours: 5, Cost: 10}); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := at(1, &Limit{Period: "week", Cost: 50}); err != nil { + t.Fatal(err) + } + if err := at(2, &Limit{Period: "days", Days: 30, Tokens: 1_000_000}); err != nil { + t.Fatal(err) + } + ls := limits() + if len(ls) != 3 || ls[0].Hours != 5 || ls[1].Period != "week" || ls[2].Days != 30 || !ls[2].Since.Equal(clock) { + t.Fatalf("three limits kept as %+v %+v %+v", ls[0], ls[1], ls[2]) + } + // the first is where an older magpie reads a key's limit + b, _ := os.ReadFile(Path()) + var saved []map[string]json.RawMessage + if err := json.Unmarshal(b, &saved); err != nil { + t.Fatal(err) + } + if !strings.Contains(string(saved[0]["limit"]), `"hours": 5`) || !strings.Contains(string(saved[0]["moreLimits"]), `"week"`) { + t.Fatalf("saved as %s", b) + } + if err := at(3, &Limit{Period: "week", Tokens: 5}); err == nil || !strings.Contains(err.Error(), "already has a limit") { + t.Fatalf("a second week limit: %v", err) + } + if err := at(5, &Limit{Period: "day", Tokens: 5}); err == nil { + t.Fatal("a limit past the end was added") + } + if err := at(3, &Limit{Period: "day", Tokens: 5}); err != nil { + t.Fatal(err) + } + if err := at(4, &Limit{Period: "month", Tokens: 5}); err != nil { + t.Fatal(err) + } + if err := at(5, &Limit{Period: "hours", Hours: 1, Tokens: 5}); err == nil || !strings.Contains(err.Error(), "at most") { + t.Fatalf("a sixth limit: %v", err) + } + // changing one keeps its cycle and leaves the others alone + clock = clock.Add(time.Hour) + if err := at(2, &Limit{Period: "days", Days: 30, Tokens: 2_000_000}); err != nil { + t.Fatal(err) + } + if ls := limits(); len(ls) != 5 || ls[2].Tokens != 2_000_000 || !ls[2].Since.Equal(clock.Add(-time.Hour)) || ls[0].Cost != 10 { + t.Fatalf("after a change: %+v", ls[2]) + } + // one reset, then all + if _, err := Update("reset-limit-key", Change{Key: id, Index: new(1)}); err != nil { + t.Fatal(err) + } + if ls := limits(); !ls[1].Since.Equal(clock) || ls[0].Since.Equal(clock) { + t.Fatalf("reset one: %+v %+v", ls[0], ls[1]) + } + clock = clock.Add(time.Hour) + if _, err := Update("reset-limit-key", Change{Key: id}); err != nil { + t.Fatal(err) + } + for i, l := range limits() { + if !l.Since.Equal(clock) { + t.Fatalf("reset all left limit %d at %s", i, l.Since) + } + } + // removing the first moves the next into its place + for range 4 { + if err := at(0, nil); err != nil { + t.Fatal(err) + } + } + keys, _ = List() + if l := keys[0].Limit; l == nil || l.Period != "month" || keys[0].More != nil { + t.Fatalf("after removing four: %+v %+v", l, keys[0].More) + } + // the single-limit form makes one the only limit again + at(1, &Limit{Period: "day", Tokens: 9}) + if _, err := Update("limit-key", Change{Key: id, Limit: &Limit{Period: "week", Tokens: 7}}); err != nil { + t.Fatal(err) + } + if ls := limits(); len(ls) != 1 || ls[0].Period != "week" { + t.Fatalf("the single form left %d limits", len(ls)) + } + who, ok := Authenticate(secret) + if !ok || len(who.Limits()) != 1 { + t.Fatalf("authenticated with %+v", who) + } + at(1, &Limit{Period: "day", Tokens: 9}) + if who, _ := Authenticate(secret); len(who.Limits()) != 2 || who.More[0].Period != "day" { + t.Fatalf("authenticated without its second limit: %+v", who.More) + } +} diff --git a/internal/budget/budget.go b/internal/budget/budget.go index 4985c432b..2c5548728 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -21,6 +21,10 @@ // size in tokens (4 bytes a token) plus the key's mean output per // call this window. A request is let in while used + reserved is // under the cap, so parallel requests overshoot by about one call. +// - A key can have several limits, each in its own window (#2227: 5 +// hours and a week, as a subscription's): a request is let in only +// while every one has something left, and its reservation is held +// in each window. // - Only requests that came with a gateway key are limited: from // another computer one is required; on this one a request without one // (or with a token that is no key) isn't limited. @@ -29,6 +33,7 @@ package budget import ( "encoding/json" "fmt" + "slices" "strings" "sync" "time" @@ -83,9 +88,9 @@ type window struct { var state = struct { sync.Mutex - sums map[string]*sums // by usage.Path() and key + sums map[string][]*sums // by usage.Path() and key, one a window its limits count in held map[window]*held -}{sums: map[string]*sums{}, held: map[window]*held{}} +}{sums: map[string][]*sums{}, held: map[window]*held{}} func slot(keyID string) string { return usage.Path() + "\x00" + keyID } @@ -94,16 +99,30 @@ func slot(keyID string) string { return usage.Path() + "\x00" + keyID } // magpie, and may be a backfill of calls long past. func counts(r usage.Record) bool { return !r.IsRejected() && !r.IsReported() && r.Computer == "" } -// sumsFor is keyID's sums for the window starting at start, read from -// usage.jsonl the first time. Called with state held. -func sumsFor(keyID string, start time.Time) *sums { +// sumsFor is keyID's sums for each window starting at starts, read from +// usage.jsonl the first time; those of windows no limit counts in now +// are let go. Called with state held. +func sumsFor(keyID string, starts []time.Time) []*sums { k := slot(keyID) - if s := state.sums[k]; s != nil && s.start.Equal(start) { - return s + kept := state.sums[k] + out := make([]*sums, len(starts)) + var next []*sums + for i, start := range starts { + j := slices.IndexFunc(kept, func(s *sums) bool { return s.start.Equal(start) }) + if j < 0 { + j = slices.IndexFunc(next, func(s *sums) bool { return s.start.Equal(start) }) + if j >= 0 { + out[i] = next[j] + continue + } + out[i] = read(keyID, start) + } else { + out[i] = kept[j] + } + next = append(next, out[i]) } - s := read(keyID, start) - state.sums[k] = s - return s + state.sums[k] = next + return out } func read(keyID string, start time.Time) *sums { @@ -122,7 +141,7 @@ func read(keyID string, start time.Time) *sums { func Forget() { state.Lock() defer state.Unlock() - state.sums = map[string]*sums{} + state.sums = map[string][]*sums{} state.held = map[window]*held{} } @@ -140,12 +159,16 @@ func Append(rec usage.Record) { rec.Time = time.Now() } usage.Append(rec) - s := state.sums[slot(rec.CallerKeyID)] - if s == nil || !counts(rec) || rec.Time.Before(s.start) { + kept := state.sums[slot(rec.CallerKeyID)] + if len(kept) == 0 || !counts(rec) { return } c, ok := usage.NewCoster()(rec) - s.add(rec, c, ok) + for _, s := range kept { + if !rec.Time.Before(s.start) { + s.add(rec, c, ok) + } + } } // Status is a key's limit and what it has used of it. @@ -191,20 +214,74 @@ func status(keyID string, l *access.Limit, s *sums, h *held, reset time.Time) St return st } -// Of is key k's status now, nil when it has no limit. It reads the file -// afresh rather than the gateway's sums, so it is right for a gateway -// served by another process too. +// Of is key k's status now of its first limit, nil when it has no limit. +// It reads the file afresh rather than the gateway's sums, so it is right +// for a gateway served by another process too. func Of(k access.Key, now time.Time) *Status { - if !k.Limit.Limited() { + all := All(k, now) + if len(all) == 0 { return nil } - start, reset := k.Limit.Window(now) - s := read(k.ID, start) - state.Lock() - h := state.held[window{slot(k.ID), start.Unix()}] - st := status(k.ID, k.Limit, s, h, reset) - state.Unlock() - return &st + return &all[0] +} + +// All is key k's status now of each of its limits (#2227), in the +// order k keeps them; none for a key with no limit. A window two +// limits share is read once. +func All(k access.Key, now time.Time) []Status { + ls := k.Limits() + var out []Status + read1 := map[int64]*sums{} + for _, l := range ls { + start, reset := l.Window(now) + s := read1[start.Unix()] + if s == nil { + s = read(k.ID, start) + read1[start.Unix()] = s + } + state.Lock() + h := state.held[window{slot(k.ID), start.Unix()}] + out = append(out, status(k.ID, l, s, h, reset)) + state.Unlock() + } + return out +} + +// Binding is the one of a key's statuses that holds it most: of those +// spent, the one that resets last, as the key is refused until then; +// else the one with the most of a cap used. Nil for none. +func Binding(all []Status) *Status { + var b *Status + for i := range all { + st := &all[i] + switch { + case b == nil: + b = st + case st.Spent != b.Spent: + if st.Spent { + b = st + } + case st.Spent: + if st.Reset.After(b.Reset) { + b = st + } + case st.share() > b.share(): + b = st + } + } + return b +} + +// share is how much of its fuller cap st has used, 0 to 1 and over. +func (st *Status) share() float64 { + var f float64 + if st.TokenLimit > 0 { + f = float64(st.Tokens) / float64(st.TokenLimit) + } + if st.CostLimit > 0 { + f = max(f, st.Cost/st.CostLimit) + } + return f } // Refusal is why a key's request was turned away. @@ -243,49 +320,91 @@ func (r *Refusal) RetryAfter(now time.Time) int { // size in bytes (-1 unknown) and model the model it named, for a cost cap // before the key has a price of its own this window. func Reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused *Refusal) { - l := who.Limit - if who.KeyID == "" || !l.Limited() { + ls := who.Limits() + if who.KeyID == "" || len(ls) == 0 { return func() {}, nil } - start, reset := l.Window(now) + starts := make([]time.Time, len(ls)) + resets := make([]time.Time, len(ls)) + for i, l := range ls { + starts[i], resets[i] = l.Window(now) + } state.Lock() defer state.Unlock() - k := window{slot(who.KeyID), start.Unix()} - s := sumsFor(who.KeyID, start) - h := state.held[k] - if h == nil { - h = &held{} - state.held[k] = h - } - used := s.tokens(l) - if (l.Tokens > 0 && used+h.tokens >= l.Tokens) || (l.Cost > 0 && s.cost+h.cost >= l.Cost) { - return nil, &Refusal{Status: status(who.KeyID, l, s, h, reset), Key: who.KeyName} - } - est := max(body, 0) / 4 - if s.calls > 0 { - est += s.output / int64(s.calls) - } - var cost float64 - if l.Cost > 0 { - if used > 0 && s.cost > 0 { - cost = float64(est) * s.cost / float64(used) - } else if p, ok := priceOf(model); ok { - cost = float64(est) * p + ss := sumsFor(who.KeyID, starts) + heldAt := func(start time.Time) *held { return state.held[window{slot(who.KeyID), start.Unix()}] } + // every limit is asked: of those with nothing left, the one that + // resets last is the one the client is told, as it is refused until then + for i, l := range ls { + s, h := ss[i], heldAt(starts[i]) + var ht int64 + var hc float64 + if h != nil { + ht, hc = h.tokens, h.cost + } + if (l.Tokens > 0 && s.tokens(l)+ht >= l.Tokens) || (l.Cost > 0 && s.cost+hc >= l.Cost) { + if refused == nil || resets[i].After(refused.Reset) { + refused = &Refusal{Status: status(who.KeyID, l, s, h, resets[i]), Key: who.KeyName} + } } } - h.n++ - h.tokens += est - h.cost += cost + if refused != nil { + return nil, refused + } + // one reservation a window, however many of the key's limits count + // in it, at that window's pace + type hold struct { + k window + h *held + est int64 + cost float64 + } + var holds []hold + for i, l := range ls { + k := window{slot(who.KeyID), starts[i].Unix()} + j := slices.IndexFunc(holds, func(x hold) bool { return x.k == k }) + if j < 0 { + s := ss[i] + est := max(body, 0) / 4 + if s.calls > 0 { + est += s.output / int64(s.calls) + } + holds = append(holds, hold{k: k, est: est}) + j = len(holds) - 1 + } + x := &holds[j] + if l.Cost > 0 && x.cost == 0 { + s, used := ss[i], ss[i].tokens(l) + if used > 0 && s.cost > 0 { + x.cost = float64(x.est) * s.cost / float64(used) + } else if p, ok := priceOf(model); ok { + x.cost = float64(x.est) * p + } + } + } + for i := range holds { + x := &holds[i] + x.h = state.held[x.k] + if x.h == nil { + x.h = &held{} + state.held[x.k] = x.h + } + x.h.n++ + x.h.tokens += x.est + x.h.cost += x.cost + } once := sync.Once{} return func() { once.Do(func() { state.Lock() defer state.Unlock() - h.n-- - h.tokens -= est - h.cost -= cost - if h.n == 0 && state.held[k] == h { - delete(state.held, k) + for _, x := range holds { + x.h.n-- + x.h.tokens -= x.est + x.h.cost -= x.cost + if x.h.n == 0 && state.held[x.k] == x.h { + delete(state.held, x.k) + } } }) }, nil diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index f97c30c92..2e462f380 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -55,7 +55,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 -] | rotate | remove | limit [off | day|week|month [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] | rotate | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...]") } switch action { case "list", "add", "rotate", "remove": @@ -115,91 +115,111 @@ func gatewayKeysTo(out io.Writer, args []string) error { return err } -// gatewayKeyLimit shows or sets a key's limit (#585): +// gatewayKeyLimit shows or sets a key's limits (#585, several since #2227): // -// magpie gateway-key limit what it has used of its limit +// magpie gateway-key limit [list] what it has used of each limit // magpie gateway-key limit off no limit // magpie gateway-key limit day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] -// magpie gateway-key limit reset count from 0 again, a new N-day or N-hour cycle from now (#1509) +// its only limit, or the one of several with that window +// magpie gateway-key limit add [--tokens N] [--cost USD] [--cache-reads] +// one more limit; a request passes only while every one has something left +// magpie gateway-key limit remove take off the nth limit +// magpie gateway-key limit reset [] count from 0 again, every limit or the nth; a new N-day or N-hour cycle from now (#1509) func gatewayKeyLimit(out io.Writer, args []string) error { - usage := fmt.Errorf("usage: magpie gateway-key limit [off | reset | day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]]") + usage := fmt.Errorf("usage: magpie gateway-key limit [off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]]") if len(args) == 0 { return usage } id := args[0] if len(args) > 1 { - var lim *access.Limit - if args[1] == "reset" { + 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") + } + have := keys[i].Limits() + // nth reads a limit's number as the list shows it, from 1 + nth := func(v string) (*int, error) { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > len(have) { + if len(have) == 0 { + return nil, fmt.Errorf("%s has no limit", keys[i].Name) + } + return nil, fmt.Errorf("a limit's number is 1 to %d, as `magpie gateway-key limit %s` lists them: %q", len(have), id, v) + } + n-- + return &n, nil + } + switch args[1] { + case "list": if len(args) > 2 { return usage } - if _, err := access.Update("reset-limit-key", access.Change{Key: id}); err != nil { + case "reset": + in := access.Change{Key: id} + if len(args) > 3 { + return usage + } + if len(args) == 3 { + if in.Index, err = nth(args[2]); err != nil { + return err + } + } + if _, err := access.Update("reset-limit-key", in); err != nil { return err } - } else if args[1] != "off" { - lim = &access.Limit{Period: args[1]} - if n, ok := strings.CutSuffix(args[1], "d"); ok { - days, err := strconv.Atoi(n) - if err != nil || days < 1 || days > access.MaxDays { - return fmt.Errorf("an N-day cycle is a whole number of days from 1 to %d, like 10d: %q", access.MaxDays, args[1]) - } - lim = &access.Limit{Period: "days", Days: days} - } else if n, ok := strings.CutSuffix(args[1], "h"); ok { - // every N hours (#2102), a subscription's 5-hour window's pace - hours, err := strconv.Atoi(n) - if err != nil || hours < 1 || hours > access.MaxHours { - return fmt.Errorf("an N-hour cycle is a whole number of hours from 1 to %d, like 5h: %q", access.MaxHours, args[1]) - } - lim = &access.Limit{Period: "hours", Hours: hours} - } else if !slices.Contains(access.Periods, lim.Period) || lim.Period == "days" || lim.Period == "hours" { - return fmt.Errorf("a limit's period is day, week, month, d (every N days) or h (every N hours), not %q", lim.Period) + case "off": + if len(args) > 2 { + return usage } - rest := args[2:] - for i := 0; i < len(rest); i++ { - flag, val, has := strings.Cut(rest[i], "=") - next := func() (string, error) { - if has { - return val, nil - } - if i+1 >= len(rest) { - return "", fmt.Errorf("%s needs a value", flag) - } - i++ - return rest[i], nil - } - switch flag { - case "--tokens": - v, err := next() - if err != nil { - return err - } - n, err := parseTokens(v) - if err != nil || n < 0 { - return fmt.Errorf("--tokens is a count, like 1000000 or 2m: %q", v) - } - lim.Tokens = int64(n) - case "--cost": - v, err := next() - if err != nil { - return err - } - if lim.Cost, err = strconv.ParseFloat(strings.TrimPrefix(v, "$"), 64); err != nil { - return fmt.Errorf("--cost is US dollars, like 5 or 2.50: %q", v) - } - case "--cache-reads": - lim.CacheReads = true - default: - return usage - } + if _, err := access.Update("limit-key", access.Change{Key: id}); err != nil { + return err } - if !lim.Limited() { - return fmt.Errorf("say --tokens, --cost or both, or off for no limit") + case "remove": + if len(args) != 3 { + return usage } - } else if len(args) > 2 { - return usage - } - if args[1] != "reset" { - if _, err := access.Update("limit-key", access.Change{Key: id, Limit: lim}); err != nil { + n, err := nth(args[2]) + if err != nil { + return err + } + if _, err := access.Update("limit-key", access.Change{Key: id, Index: n}); err != nil { + return err + } + case "add": + if len(args) < 3 { + return usage + } + lim, err := parseKeyLimit(args[2], args[3:], usage) + if err != nil { + return err + } + n := len(have) + if _, err := access.Update("limit-key", access.Change{Key: id, Limit: lim, Index: &n}); err != nil { + return err + } + default: + lim, err := parseKeyLimit(args[1], args[2:], usage) + if err != nil { + return err + } + in := access.Change{Key: id, Limit: lim} + // of several, the one counted in the same window is set; the + // only one is replaced, as before #2227 + if len(have) > 1 { + v, _ := lim.Valid() + n := slices.IndexFunc(have, func(l *access.Limit) bool { + return v != nil && l.Period == v.Period && l.Days == v.Days && l.Hours == v.Hours + }) + if n < 0 { + return fmt.Errorf("%s has %d limits and none %s: add one with `magpie gateway-key limit %s add %s ...`, or take one off with `remove `", keys[i].Name, len(have), perPhrase(v), id, args[1]) + } + in.Index = &n + } + if _, err := access.Update("limit-key", in); err != nil { return err } } @@ -213,40 +233,124 @@ func gatewayKeyLimit(out io.Writer, args []string) error { return fmt.Errorf("Key not found") } k, now := keys[i], time.Now() - st := budget.Of(k, now) - if st == nil { + all := budget.All(k, now) + if len(all) == 0 { _, err = fmt.Fprintf(out, "%s: no limit\n", k.Name) return err } w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) fmt.Fprintf(w, "Key\t%s (%s)\n", k.Name, k.ID) - fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", (&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}).Per(), st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04")) - if st.TokenLimit > 0 { - counted := "input, output and cache writes" - if st.CacheReads { - counted += ", and cache reads" + for n, st := range all { + if len(all) > 1 { + fmt.Fprintf(w, "\t\n") + fmt.Fprintf(w, "Limit %d\t%s, all must have something left\n", n+1, perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours})) } - fmt.Fprintf(w, "Tokens\t%d used of %d, %d left (%s)\n", st.Tokens, st.TokenLimit, st.TokensLeft, counted) - } else { - fmt.Fprintf(w, "Tokens\t%d used, no cap\n", st.Tokens) + fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", (&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}).Per(), st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04")) + if st.TokenLimit > 0 { + counted := "input, output and cache writes" + if st.CacheReads { + counted += ", and cache reads" + } + fmt.Fprintf(w, "Tokens\t%d used of %d, %d left (%s)\n", st.Tokens, st.TokenLimit, st.TokensLeft, counted) + } else { + fmt.Fprintf(w, "Tokens\t%d used, no cap\n", st.Tokens) + } + unpriced := "" + if st.Unpriced > 0 { + unpriced = fmt.Sprintf(", %d calls without a known price not in it", st.Unpriced) + } + if st.CostLimit > 0 { + fmt.Fprintf(w, "Cost\t$%.2f used of $%.2f, $%.2f left (estimate at Usage prices%s)\n", st.Cost, st.CostLimit, st.CostLeft, unpriced) + } else { + fmt.Fprintf(w, "Cost\t$%.2f used, no cap (estimate%s)\n", st.Cost, unpriced) + } + state := "open" + if st.Spent { + state = "spent: requests are refused until " + st.Reset.Format("2006-01-02 15:04") + } + fmt.Fprintf(w, "State\t%s\n", state) } - unpriced := "" - if st.Unpriced > 0 { - unpriced = fmt.Sprintf(", %d calls without a known price not in it", st.Unpriced) - } - if st.CostLimit > 0 { - fmt.Fprintf(w, "Cost\t$%.2f used of $%.2f, $%.2f left (estimate at Usage prices%s)\n", st.Cost, st.CostLimit, st.CostLeft, unpriced) - } else { - fmt.Fprintf(w, "Cost\t$%.2f used, no cap (estimate%s)\n", st.Cost, unpriced) - } - state := "open" - if st.Spent { - state = "spent: requests are refused until " + st.Reset.Format("2006-01-02 15:04") - } - fmt.Fprintf(w, "State\t%s\n", state) return w.Flush() } +// perPhrase is a limit's window as the CLI says it: "per week", "every 5 +// hours". +func perPhrase(l *access.Limit) string { + if l == nil { + return "" + } + switch l.Period { + case "days": + return fmt.Sprintf("every %d days", l.Days) + case "hours": + return fmt.Sprintf("every %d hours", l.Hours) + } + return "per " + l.Period +} + +// parseKeyLimit reads a limit as typed: its window, then --tokens, +// --cost and --cache-reads. +func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, error) { + lim := &access.Limit{Period: window} + if n, ok := strings.CutSuffix(window, "d"); ok { + days, err := strconv.Atoi(n) + if err != nil || days < 1 || days > access.MaxDays { + return nil, fmt.Errorf("an N-day cycle is a whole number of days from 1 to %d, like 10d: %q", access.MaxDays, window) + } + lim = &access.Limit{Period: "days", Days: days} + } else if n, ok := strings.CutSuffix(window, "h"); ok { + // every N hours (#2102), a subscription's 5-hour window's pace + hours, err := strconv.Atoi(n) + if err != nil || hours < 1 || hours > access.MaxHours { + return nil, fmt.Errorf("an N-hour cycle is a whole number of hours from 1 to %d, like 5h: %q", access.MaxHours, window) + } + lim = &access.Limit{Period: "hours", Hours: hours} + } else if !slices.Contains(access.Periods, lim.Period) || lim.Period == "days" || lim.Period == "hours" { + return nil, fmt.Errorf("a limit's period is day, week, month, d (every N days) or h (every N hours), not %q", lim.Period) + } + for i := 0; i < len(rest); i++ { + flag, val, has := strings.Cut(rest[i], "=") + next := func() (string, error) { + if has { + return val, nil + } + if i+1 >= len(rest) { + return "", fmt.Errorf("%s needs a value", flag) + } + i++ + return rest[i], nil + } + switch flag { + case "--tokens": + v, err := next() + if err != nil { + return nil, err + } + n, err := parseTokens(v) + if err != nil || n < 0 { + return nil, fmt.Errorf("--tokens is a count, like 1000000 or 2m: %q", v) + } + lim.Tokens = int64(n) + case "--cost": + v, err := next() + if err != nil { + return nil, err + } + if lim.Cost, err = strconv.ParseFloat(strings.TrimPrefix(v, "$"), 64); err != nil { + return nil, fmt.Errorf("--cost is US dollars, like 5 or 2.50: %q", v) + } + case "--cache-reads": + lim.CacheReads = true + default: + return nil, usage + } + } + if !lim.Limited() { + return nil, fmt.Errorf("say --tokens, --cost or both, or off for no limit") + } + return lim, nil +} + // gatewayKeyModels shows or sets the models a key may use (#882): // // magpie gateway-key models the models it may use @@ -283,32 +387,29 @@ func gatewayKeyModels(out io.Writer, args []string) error { return err } -// limitWords is a key's limit in the list: "-" for none, else what it has -// used of it, "1200/1000000 tokens/day". +// limitWords is a key's limits in the list: "-" for none, else what it +// has used of each, "1200/1000000 tokens per day; $1.00/$20.00 per week". func limitWords(k access.Key, now time.Time) string { - st := budget.Of(k, now) - if st == nil { + all := budget.All(k, now) + if len(all) == 0 { return "-" } - var parts []string - if st.TokenLimit > 0 { - parts = append(parts, fmt.Sprintf("%d/%d tokens", st.Tokens, st.TokenLimit)) + var each []string + for _, st := range all { + var parts []string + if st.TokenLimit > 0 { + parts = append(parts, fmt.Sprintf("%d/%d tokens", st.Tokens, st.TokenLimit)) + } + if st.CostLimit > 0 { + parts = append(parts, fmt.Sprintf("$%.2f/$%.2f", st.Cost, st.CostLimit)) + } + s := strings.Join(parts, " ") + " " + perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}) + if st.Spent { + s += " (spent until " + st.Reset.Format("01-02 15:04") + ")" + } + each = append(each, s) } - if st.CostLimit > 0 { - parts = append(parts, fmt.Sprintf("$%.2f/$%.2f", st.Cost, st.CostLimit)) - } - per := " per " + st.Period - switch st.Period { - case "days": - per = fmt.Sprintf(" every %d days", st.Days) - case "hours": - per = fmt.Sprintf(" every %d hours", st.Hours) - } - s := strings.Join(parts, " ") + per - if st.Spent { - s += " (spent until " + st.Reset.Format("01-02 15:04") + ")" - } - return s + return strings.Join(each, "; ") } // gatewayKeyAccounts shows or sets a key's account whitelist (#905): the diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index 5171ba4c4..c0ebbe851 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -311,3 +311,84 @@ func TestGatewayKeyAccountsCLI(t *testing.T) { t.Fatal("all kept accounts", keys[0].Accounts) } } + +// magpie gateway-key limit adds, lists, changes and removes a key's +// several limits (#2227); the single-limit form still sets an only limit. +func TestGatewayKeySeveralLimitsCLI(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 + limits := func() []*access.Limit { + keys, _ := access.List() + return keys[0].Limits() + } + if _, err := call("limit", id, "add", "5h", "--cost", "10"); err != nil { + t.Fatal(err) + } + got, err := call("limit", id, "add", "week", "--cost", "50") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"Limit 1", "every 5 hours", "Limit 2", "per week", "this 5-hour cycle", "this week", "$10.00", "$50.00"} { + if !strings.Contains(got, want) { + t.Fatalf("two limits show %q, without %q", got, want) + } + } + if list, err := call("limit", id, "list"); err != nil || list != got { + t.Fatal("list:", list, err) + } + // the plain form changes the one with that window + if _, err := call("limit", id, "week", "--cost", "60"); err != nil { + t.Fatal(err) + } + if ls := limits(); len(ls) != 2 || ls[1].Cost != 60 || ls[0].Cost != 10 { + t.Fatalf("after changing the week: %+v %+v", ls[0], ls[1]) + } + for _, args := range [][]string{{"limit", id, "day", "--tokens", "5"}, {"limit", id, "add", "week", "--tokens", "5"}, {"limit", id, "remove", "3"}, + {"limit", id, "remove"}, {"limit", id, "remove", "x"}, {"limit", id, "reset", "0"}, {"limit", id, "list", "extra"}, {"limit", id, "add"}} { + if _, err := call(args...); err == nil { + t.Fatal("accepted", args) + } + } + if ls := limits(); len(ls) != 2 { + t.Fatalf("a refused command left %d limits", len(ls)) + } + if _, err := call("limit", id, "reset", "2"); err != nil { + t.Fatal(err) + } + if _, err := call("limit", id, "remove", "1"); err != nil { + t.Fatal(err) + } + if ls := limits(); len(ls) != 1 || ls[0].Period != "week" { + t.Fatalf("after removing the first: %+v", ls) + } + if got, err := call("limit", id); err != nil || strings.Contains(got, "Limit 1") || !strings.Contains(got, "this week") { + t.Fatal("one limit shows", got, err) + } + // the single form, with one limit, replaces it as before + if _, err := call("limit", id, "day", "--tokens", "5"); err != nil { + t.Fatal(err) + } + if ls := limits(); len(ls) != 1 || ls[0].Period != "day" { + t.Fatalf("the single form: %+v", ls) + } + if _, err := call("limit", id, "remove", "1"); err != nil { + t.Fatal(err) + } + if got, err := call("limit", id); err != nil || !strings.Contains(got, "no limit") { + t.Fatal(got, err) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index fa87681a0..a5669aabf 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -115,7 +115,7 @@ const usage = `magpie — one place to pick every agent's model the service's page: its link, or turn it on or off magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK) magpie gateway-key list|add |rotate |remove manage the keys clients use to call a shared gateway - magpie gateway-key limit [off|reset|day|week|month|d|h --tokens N --cost USD --cache-reads] a key's own limit, and what it used + magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads] a key's own limits, and what it used magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some magpie mcp image the image and video generation MCP server an agent is given from the library (stdio) magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d) diff --git a/internal/gateway/key_limit.go b/internal/gateway/key_limit.go index a7da11ebc..b3a852322 100644 --- a/internal/gateway/key_limit.go +++ b/internal/gateway/key_limit.go @@ -4,6 +4,7 @@ import ( "bytes" "io" "net/http" + "slices" "strconv" "strings" "time" @@ -32,13 +33,15 @@ const remoteKeyLimitHeader = "X-Magpie-Limit-Reset" func keyLimited(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { who := access.Caller(r.Context()) - if !who.Limit.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") { + limits := who.Limits() + if len(limits) == 0 || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") { next.ServeHTTP(w, r) return } size, model := r.ContentLength, "" // a compressed body (#1223) is reserved at its decoded size and model - if enc := r.Header.Get("Content-Encoding"); who.Limit.Cost > 0 || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) { + costCap := slices.ContainsFunc(limits, func(l *access.Limit) bool { return l.Cost > 0 }) + if enc := r.Header.Get("Content-Encoding"); costCap || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) { b, status, err := readBoundedRequestBody(w, r, requestLimits{}) if err != nil { writeError(w, protoOfPath(r.URL.Path), status, err.Error()) @@ -81,13 +84,15 @@ func protoOfPath(path string) provider.Protocol { // keyLimit answers GET /v1/magpie/limit: the calling gateway key's limit, // what it has used and when it resets; {"limited":false} for a key with -// none or a request without one. +// none or a request without one. "limits" is each of a key's limits +// (#2227), and "limit" the one holding it most (budget.Binding), which is +// what a magpie from before them reads. func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) { who := access.Caller(r.Context()) - if who.KeyID == "" || !who.Limit.Limited() { + if who.KeyID == "" || len(who.Limits()) == 0 { writeJSON(w, 200, map[string]any{"limited": false, "key": who.KeyName}) return } - st := budget.Of(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit}, limitClock()) - writeJSON(w, 200, map[string]any{"limited": true, "key": who.KeyName, "limit": st}) + all := budget.All(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit, More: who.More}, limitClock()) + writeJSON(w, 200, map[string]any{"limited": true, "key": who.KeyName, "limit": budget.Binding(all), "limits": all}) } diff --git a/internal/gateway/key_limit_test.go b/internal/gateway/key_limit_test.go index e909d185f..802a0143d 100644 --- a/internal/gateway/key_limit_test.go +++ b/internal/gateway/key_limit_test.go @@ -514,3 +514,86 @@ func TestKeyLimitHoursCycle(t *testing.T) { t.Fatal("refused after Reset", w.Code, w.Body.String()) } } + +// A key with several limits (#2227) is let in only while every one has +// something left: any one spent refuses it, and the 429 names the spent +// one that resets last, as the key is refused until then. A request held +// in flight counts in each limit's window; /v1/magpie/limit reports each. +func TestKeyLimitSeveralLimits(t *testing.T) { + fresh(t) + budget.Forget() + t.Cleanup(budget.Forget) + now := pinLimitClock(t) + calls := limitedUpstream(t, 0) + keys, secrets := newCaller(t, "Shared") + at := func(n int, l *access.Limit) { + t.Helper() + if _, err := access.Update("limit-key", access.Change{Key: keys[0].ID, Limit: l, Index: &n}); err != nil { + t.Fatal(err) + } + } + at(0, &access.Limit{Period: "day", Tokens: 700}) + at(1, &access.Limit{Period: "week", Tokens: 5000}) + h := New().Handler() + call := func(method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+secrets[0]) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + ks, _ := access.List() + who := access.Identity{KeyID: keys[0].ID, KeyName: "Shared", Limit: ks[0].Limit, More: ks[0].More} + // one in flight is held in the day's window and the week's + release, refused := budget.Reserve(who, 400, "", now) + if refused != nil { + t.Fatal(refused) + } + all := budget.All(ks[0], now) + if len(all) != 2 || all[0].InFlight != 1 || all[1].InFlight != 1 || all[0].Period != "day" || all[1].Period != "week" { + t.Fatalf("in flight: %+v", all) + } + release() + if all := budget.All(ks[0], now); all[0].InFlight != 0 || all[1].InFlight != 0 { + t.Fatalf("released: %+v", all) + } + for i := range 2 { + if w := call("POST", "/v1/chat/completions", chatReq); w.Code != 200 { + t.Fatal("within both limits", i, w.Code, w.Body.String()) + } + } + // the day is spent, the week isn't: refused, until the day resets + _, endOfDay := access.Window("day", now) + _, endOfWeek := access.Window("week", now) + w := call("POST", "/v1/chat/completions", chatReq) + if w.Code != 429 || calls.Load() != 2 || w.Header().Get("X-Magpie-Limit-Reset") != endOfDay.Format(time.RFC3339) { + t.Fatal("day spent:", w.Code, calls.Load(), w.Header(), w.Body.String()) + } + // both spent: the week is the one that holds it longest + at(1, &access.Limit{Period: "week", Tokens: 700}) + w = call("POST", "/v1/chat/completions", chatReq) + if w.Code != 429 || w.Header().Get("X-Magpie-Limit-Reset") != endOfWeek.Format(time.RFC3339) || + w.Header().Get("Retry-After") != strconv.Itoa(int(endOfWeek.Sub(now).Seconds())) { + t.Fatal("both spent:", w.Code, w.Header(), w.Body.String()) + } + var got struct { + Limited bool + Limit budget.Status + Limits []budget.Status + } + lim := call("GET", "/v1/magpie/limit", "") + json.Unmarshal(lim.Body.Bytes(), &got) + if !got.Limited || len(got.Limits) != 2 || got.Limit.Period != "week" || !got.Limits[0].Spent || !got.Limits[1].Spent || got.Limits[0].Tokens != 700 { + t.Fatal("/v1/magpie/limit:", lim.Body.String()) + } + // the day's limit raised: the week still refuses + at(0, &access.Limit{Period: "day", Tokens: 5000}) + if w := call("POST", "/v1/chat/completions", chatReq); w.Code != 429 || w.Header().Get("X-Magpie-Limit-Reset") != endOfWeek.Format(time.RFC3339) { + t.Fatal("week spent:", w.Code, w.Body.String()) + } + // the week's taken off: in again + at(1, nil) + if w := call("POST", "/v1/chat/completions", chatReq); w.Code != 200 { + t.Fatal("the day alone has room:", w.Code, w.Body.String()) + } +} diff --git a/internal/gateway/remote_key_limits_test.go b/internal/gateway/remote_key_limits_test.go index a7ea26ff6..e72ffef77 100644 --- a/internal/gateway/remote_key_limits_test.go +++ b/internal/gateway/remote_key_limits_test.go @@ -121,6 +121,17 @@ func TestRemoteMagpieKeyLimitCards(t *testing.T) { l.Windows[0].Name != "Tokens this cycle" || !l.GatewayKey.Reset.Equal(l.GatewayKey.Start.Add(5*time.Hour)) { t.Errorf("laptop every 5 hours: %+v %+v", l, l.GatewayKey) } + // and a week beside it (#2227): a window for each, the key told of the + // one holding it most + n := 1 + if _, err := access.Update("limit-key", access.Change{Key: keys[0].ID, Limit: &access.Limit{Period: "week", Tokens: 300}, Index: &n}); err != nil { + t.Fatal(err) + } + provider.RefreshUsage(ctx, "office/~keys", "laptop") + if l := cards()["laptop"]; len(l.Windows) != 2 || l.Windows[0].Name != "Tokens this cycle" || l.Windows[1].Name != "Tokens this week" || + l.Windows[1].Amount != 350 || l.Windows[1].Limit != 300 || l.GatewayKey.Period != "week" || !l.GatewayKey.Spent { + t.Errorf("laptop with two limits: %+v %+v", l, l.GatewayKey) + } } // A key asking after its limit is told its own, whatever the request diff --git a/internal/gateway/usage_api.go b/internal/gateway/usage_api.go index 72f65bd10..1abee3dd3 100644 --- a/internal/gateway/usage_api.go +++ b/internal/gateway/usage_api.go @@ -27,7 +27,7 @@ const usageRefused = "magpie's usage is told to another machine only when magpie // heldKey: the request's gateway key is held to a budget, models or // accounts, and so sees only its own usage. func heldKey(who access.Identity) bool { - return who.KeyID != "" && (who.Limit.Limited() || len(who.Models) > 0 || len(who.Accounts) > 0) + return who.KeyID != "" && (len(who.Limits()) > 0 || len(who.Models) > 0 || len(who.Accounts) > 0) } // heldRefused is what a held key is told where this magpie's own accounts diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 80b2c21a2..cf9876c0a 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2499,6 +2499,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } #gatewayKeys .klf-used { display: flex; align-items: center; gap: 8px; min-width: 0; } #gatewayKeys .klf-used .key-limit { flex: 1 1 auto; } #gatewayKeys .klf-used .klf-reset { flex: none; } +/* a key's several limits (#2227): one tab each, the editor is of one */ +#gatewayKeys .klf-which { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; } +#gatewayKeys .klf-tab { height: 24px; padding: 0 10px; border-radius: 6px; font-size: 12px; color: var(--ctl-fg); white-space: nowrap; } +#gatewayKeys .klf-tab:hover:not(.on) { color: var(--fg-2); } +#gatewayKeys .klf-tab.on { color: var(--fg); background: var(--seg-thumb); box-shadow: var(--seg-edge); } @media (max-width: 520px) { #gatewayKeys .klf, #gatewayKeys .klf.with-days { grid-template-columns: 1fr; } #gatewayKeys .klf-used { flex-wrap: wrap; } } /* the models a key may use (#882): a long model's id is cut, and the badge gives way first on a narrow window */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 3e0fbeaf0..bcc4b2ac9 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -364,6 +364,13 @@ const I18N = { "Days in a cycle": "每个周期的天数", "Days is a whole number from 1 to 3650": "天数应为 1 到 3650 的整数", "Reset usage": "重置额度", + "+1 limit": "另 1 条限额", + "+{n} limits": "另 {n} 条限额", + "This key's limits": "这个密钥的限额", + "New limit": "新限额", + "Add a limit": "添加限额", + "Another limit in a window of its own; a request passes only while every limit has something left": "在另一个周期再设一条限额;每条限额都还有剩余时请求才放行", + "Remove this limit": "删除这条限额", "Count this key's use from 0 again, tokens and cost together": "此密钥已用的 Token 和费用一起从 0 重新计算", "Reset {name}'s usage?": "重置 {name} 的额度?", "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和费用一起清零,并从现在开始新的 {n} 天周期。", @@ -3916,6 +3923,13 @@ const I18N = { "Days in a cycle": "每個週期的天數", "Days is a whole number from 1 to 3650": "天數應為 1 到 3650 的整數", "Reset usage": "重置額度", + "+1 limit": "另 1 條限額", + "+{n} limits": "另 {n} 條限額", + "This key's limits": "這個金鑰的限額", + "New limit": "新限額", + "Add a limit": "新增限額", + "Another limit in a window of its own; a request passes only while every limit has something left": "在另一個週期再設一條限額;每條限額都還有剩餘時請求才放行", + "Remove this limit": "刪除這條限額", "Count this key's use from 0 again, tokens and cost together": "此金鑰已用的 Token 和費用一起從 0 重新計算", "Reset {name}'s usage?": "重置 {name} 的額度?", "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和費用一起歸零,並從現在開始新的 {n} 天週期。", @@ -7430,6 +7444,13 @@ const I18N = { "Days in a cycle": "1 周期の日数", "Days is a whole number from 1 to 3650": "日数は 1〜3650 の整数です", "Reset usage": "使用量をリセット", + "+1 limit": "ほか 1 件の上限", + "+{n} limits": "ほか {n} 件の上限", + "This key's limits": "このキーの上限", + "New limit": "新しい上限", + "Add a limit": "上限を追加", + "Another limit in a window of its own; a request passes only while every limit has something left": "別の期間でもう一つ上限を設定します。すべての上限に残りがあるときだけリクエストが通ります", + "Remove this limit": "この上限を削除", "Count this key's use from 0 again, tokens and cost together": "このキーのトークンと費用の使用量を一緒に 0 から数え直します", "Reset {name}'s usage?": "{name} の使用量をリセットしますか?", "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} が使ったトークンと費用を一緒に 0 に戻し、今から新しい {n} 日の周期を始めます。", @@ -10961,6 +10982,13 @@ const I18N = { "Days in a cycle": "Tage je Zyklus", "Days is a whole number from 1 to 3650": "Tage sind eine ganze Zahl von 1 bis 3650", "Reset usage": "Nutzung zurücksetzen", + "+1 limit": "+1 Limit", + "+{n} limits": "+{n} Limits", + "This key's limits": "Limits dieses Schlüssels", + "New limit": "Neues Limit", + "Add a limit": "Limit hinzufügen", + "Another limit in a window of its own; a request passes only while every limit has something left": "Ein weiteres Limit mit eigenem Zeitfenster; eine Anfrage geht nur durch, solange jedes Limit noch etwas übrig hat", + "Remove this limit": "Dieses Limit entfernen", "Count this key's use from 0 again, tokens and cost together": "Zählt Token und Kosten dieses Schlüssels zusammen wieder ab 0", "Reset {name}'s usage?": "Nutzung von {name} zurücksetzen?", "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0, und jetzt beginnt ein neuer Zyklus von {n} Tagen.", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index abd54837a..f6c79c75f 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -182,8 +182,8 @@ function renderGatewayKeys() { const rotate = el("button", "text quiet", t("Rotate key")); rotate.onclick = () => askGatewayKey(k, true); row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), el("span", "grow"), gatewayModelsBadge(k), gatewayLimitBadge(k), copyCallerKeyBtn(k), rotate, rm); - const under = gatewayLimit?.id === k.id ? gatewayLimitEditor(k) : k.used ? gatewayLimitLine(k) : null; - if (under) row.classList.add("with-limit"), row.append(under); + 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); } if (gatewayKeyDraft !== null) list.append(gatewayKeyForm()); @@ -381,10 +381,31 @@ function limitCost(v) { } const usd = (n) => "$" + (n >= 100 ? n.toFixed(0) : n.toFixed(2)); +// keyLimits are a key's limits, its first and the rest (#2227), and +// keyUsed what it has used of each, in the same order. +const keyLimits = (k) => k.limit ? [k.limit, ...(k.moreLimits || [])] : []; +const keyUsed = (k) => k.usedAll || (k.used ? [k.used] : []); +// limitDraft is the editor's draft of a key's nth limit, or of a new one +// at n past the last. +function limitDraft(k, n) { + const l = keyLimits(k)[n] || {}; + const taken = keyLimits(k).map((x) => x.period); + // a new one in a window the key has no limit in yet: a week beside 5 hours + const period = l.period || (n ? ["week", "hours", "day", "month"].find((p) => !taken.includes(p)) || "days" : "day"); + return { id: k.id, n, period, days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : (n && period === "hours" ? "5" : ""), tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads }; +} +// bindingUsed is the limit holding a key most: of those spent, the one +// that resets last, as it is refused until then; else the first +function bindingUsed(k) { + const all = keyUsed(k), spent = all.filter((u) => u.spent); + return spent.length ? spent.reduce((a, b) => (new Date(b.reset) > new Date(a.reset) ? b : a)) : all[0]; +} + // gatewayLimitBadge opens a key's limit editor: "Limit" on hover when it -// has none, else what it has used, "1.2M / 2M · day", always shown. +// has none, else what it has used, "1.2M / 2M · day", always shown; with +// several limits, the one holding it most and how many more there are. function gatewayLimitBadge(k) { - const u = k.used; + const u = bindingUsed(k), more = keyUsed(k).length - 1; const b = el("button", "amodels limit" + (u ? " set" : "") + (u?.spent ? " spent" : "") + (gatewayLimit?.id === k.id ? " open" : "")); b.type = "button"; if (!u) b.textContent = t("Limit"); @@ -392,7 +413,8 @@ function gatewayLimitBadge(k) { const parts = []; if (u.tokenLimit) parts.push(fmtN(u.tokens) + " / " + fmtN(u.tokenLimit)); if (u.costLimit) parts.push(usd(u.cost) + " / " + usd(u.costLimit)); - b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days, u.hours); + b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days, u.hours) + + (more > 0 ? " · " + t(more === 1 ? "+1 limit" : "+{n} limits", { n: more }) : ""); } b.title = t(u ? "Change this key's limit" : "Set a limit for this key"); b.setAttribute("aria-label", b.title); @@ -400,21 +422,19 @@ function gatewayLimitBadge(k) { b.onclick = (e) => { e.preventDefault(); if (gatewayLimit?.id === k.id) gatewayLimit = null; - else { - const l = k.limit || {}; - gatewayLimit = { id: k.id, period: l.period || "day", days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : "", tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads }; - } + else gatewayLimit = limitDraft(k, Math.max(0, keyUsed(k).indexOf(u))); renderGatewayKeys(); }; return b; } -// gatewayLimitLine says what a limited key has used, has left and when -// it resets, under its row. -function gatewayLimitLine(k) { - const u = k.used; +// gatewayLimitLine says what a limited key has used of a limit u, has +// left and when it resets, under its row; with several, each says its +// window first. +function gatewayLimitLine(k, u) { const line = el("div", "key-limit" + (u.spent ? " spent" : "")); const parts = []; + if (keyUsed(k).length > 1) parts.push(perWords(u.period, u.days, u.hours)); if (u.tokenLimit) parts.push(t("{used} of {limit} tokens · {left} left", { used: fmtN(u.tokens), limit: fmtN(u.tokenLimit), left: fmtN(u.tokensLeft) })); if (u.costLimit) parts.push(t("{used} of {limit} estimated · {left} left", { used: usd(u.cost), limit: usd(u.costLimit), left: usd(u.costLeft) })); const at = new Date(u.reset); @@ -431,7 +451,8 @@ function gatewayLimitEditor(k) { const d = gatewayLimit; const box = el("div", "acct-models key-limit-ed"); box.onclick = (e) => e.stopPropagation(); - const kept = k.limit || {}; + const limits = keyLimits(k), n = d.n || 0, used = keyUsed(k)[n]; + const kept = limits[n] || {}; const changed = () => d.period !== (kept.period || "day") || limitTokens(d.tokens) !== (kept.tokens || 0) || limitCost(d.cost) !== (kept.cost || 0) || d.cacheReads !== !!kept.cacheReads || (d.period === "days" && limitDays(d.days) !== kept.days) @@ -476,6 +497,29 @@ function gatewayLimitEditor(k) { const pl = el("label", "klf-field"); pl.append(el("span", "klf-name", t("Window")), period); fields.append(pl, dl, hl, tl, cl); + // a key's limits (#2227), each a tab, when it has more than one or one + // is being added: the editor is of one at a time + let which = null; + if (limits.length > 1 || n >= limits.length && limits.length) { + which = el("div", "klf-which"); + which.setAttribute("role", "tablist"); + which.setAttribute("aria-label", t("This key's limits")); + const tabs = limits.map((l, i) => ({ i, name: perWords(l.period, l.days, l.hours) })); + if (n >= limits.length) tabs.push({ i: n, name: t("New limit") }); + for (const x of tabs) { + const tab = el("button", "klf-tab" + (x.i === n ? " on" : ""), x.name); + tab.type = "button"; + tab.setAttribute("role", "tab"); + tab.setAttribute("aria-selected", String(x.i === n)); + tab.onclick = (e) => { + e.stopPropagation(); + if (x.i === n) return; + gatewayLimit = limitDraft(k, x.i); + renderGatewayKeys(); + }; + which.append(tab); + } + } const cache = el("label", "klf-check"); const cb = el("input"); cb.type = "checkbox"; @@ -494,7 +538,8 @@ function gatewayLimitEditor(k) { err.textContent = bad; err.hidden = !bad; unsaved.hidden = !changed(); - save.disabled = !!bad || !changed(); + // a limit being added has a cap to save + save.disabled = !!bad || !changed() || (n >= limits.length && !limitTokens(d.tokens) && !limitCost(d.cost)); }; period.onclick = (e) => { e.preventDefault(); @@ -528,28 +573,38 @@ function gatewayLimitEditor(k) { const limit = tk || c ? { period: d.period, tokens: tk, cost: c, cacheReads: d.cacheReads } : null; if (limit && d.period === "days") limit.days = limitDays(d.days); if (limit && d.period === "hours") limit.hours = limitHours(d.hours); - const out = await gatewayKeyAction("limit-key", { key: k.id, limit }); + // which one only when there are several: one is the key's only limit + const out = await gatewayKeyAction("limit-key", which ? { key: k.id, limit, index: n } : { key: k.id, limit }); if (!out) { update(); return; } status(t(limit ? "Limit saved for {name}" : "Limit removed for {name}", { name: k.name }), "ok"); }; const foot = el("div", "acm-foot"); foot.append(cache, el("span", "grow"), unsaved); - if (k.limit) { - const off = el("button", "text", t("No limit")); + if (limits.length && n < limits.length && limits.length < 5) { + // one more limit in a window of its own (#2227): 5 hours and a week, + // as a subscription's; a request passes only while all have some left + const more = el("button", "text", t("Add a limit")); + more.title = t("Another limit in a window of its own; a request passes only while every limit has something left"); + more.onclick = (e) => { e.stopPropagation(); gatewayLimit = limitDraft(k, limits.length); renderGatewayKeys(); }; + foot.append(more); + } + if (n < limits.length) { + const off = el("button", "text", t(limits.length > 1 ? "Remove this limit" : "No limit")); off.title = t("Clears the caps; Save makes it"); off.onclick = () => { d.tokens = ""; d.cost = ""; tokens.value = ""; cost.value = ""; update(); }; foot.append(off); } foot.append(cancel, save); + if (which) box.append(which); box.append(fields, hint, err); - if (k.used) { + if (used) { // count from 0 again, tokens and cost together (#1509) const zero = el("button", "text klf-reset", t("Reset usage")); zero.title = t("Count this key's use from 0 again, tokens and cost together"); - zero.onclick = (e) => { e.stopPropagation(); askResetLimit(k); }; - const used = el("div", "klf-used"); - used.append(gatewayLimitLine(k), zero); - box.append(used); + zero.onclick = (e) => { e.stopPropagation(); askResetLimit(k, n); }; + const line = el("div", "klf-used"); + line.append(gatewayLimitLine(k, used), zero); + box.append(line); } box.append(foot); update(); @@ -559,8 +614,8 @@ function gatewayLimitEditor(k) { // askResetLimit confirms a key's Reset (#1509): what it has used goes back // to 0, tokens and cost together; an N-day cycle starts again from now, a // calendar window keeps its end. -function askResetLimit(k) { - const u = k.used || {}; +function askResetLimit(k, n) { + const u = keyUsed(k)[n] || {}; const ed = el("div", "editor"); const head = el("div", "ehead"); head.append(el("b", "", t("Reset {name}'s usage?", { name: k.name }))); @@ -576,7 +631,7 @@ function askResetLimit(k) { e.stopPropagation(); if (go.disabled) return; go.disabled = true; - const out = await gatewayKeyAction("reset-limit-key", { key: k.id }); + const out = await gatewayKeyAction("reset-limit-key", keyUsed(k).length > 1 ? { key: k.id, index: n } : { key: k.id }); if (!out) { go.disabled = false; return; } closeConfirmAsk(); status(t("Usage reset for {name}", { name: k.name }), "ok"); diff --git a/internal/gui/caller_keys.go b/internal/gui/caller_keys.go index 77abb2bd0..4941c3ad4 100644 --- a/internal/gui/caller_keys.go +++ b/internal/gui/caller_keys.go @@ -12,10 +12,12 @@ import ( ) // keyRow is a gateway key as the Gateway page lists it, with what it has -// used of its limit (#585). +// used of its limit (#585): Used of its first, UsedAll of each (#2227), +// in the order of its limits. type keyRow struct { access.Key - Used *budget.Status `json:"used,omitempty"` + Used *budget.Status `json:"used,omitempty"` + UsedAll []budget.Status `json:"usedAll,omitempty"` } // keyModelJSON is a model a gateway key may be held to, as its picker @@ -35,7 +37,11 @@ func withLimits(keys []access.Key) []keyRow { now := time.Now() out := make([]keyRow, 0, len(keys)) for _, k := range keys { - out = append(out, keyRow{Key: k, Used: budget.Of(k, now)}) + row := keyRow{Key: k, UsedAll: budget.All(k, now)} + if len(row.UsedAll) > 0 { + row.Used = &row.UsedAll[0] + } + out = append(out, row) } return out } diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 914777b80..f362edd41 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -127,18 +127,33 @@ function fixture(lang, theme, events, options = {}) { if (action === "on-key" || action === "off-key") k.off = action === "off-key"; if (action === "limit-key") { // what a key has used is the fixture's; a new limit starts unused - k.limit = body.limit || undefined; - const span = body.limit?.period === "hours" ? body.limit.hours * 36e5 : (body.limit?.days || 1) * 864e5; - k.used = body.limit ? { period: body.limit.period, days: body.limit.days, hours: body.limit.hours, start: new Date().toISOString(), reset: new Date(Date.now() + span).toISOString(), - calls: 0, tokens: 0, cost: 0, tokenLimit: body.limit.tokens, costLimit: body.limit.cost, tokensLeft: body.limit.tokens, costLeft: body.limit.cost, spent: false } : undefined; + const usedOf = (l) => { + const span = l.period === "hours" ? l.hours * 36e5 : (l.days || 1) * 864e5; + return { period: l.period, days: l.days, hours: l.hours, start: new Date().toISOString(), reset: new Date(Date.now() + span).toISOString(), + calls: 0, tokens: 0, cost: 0, tokenLimit: l.tokens, costLimit: l.cost, tokensLeft: l.tokens, costLeft: l.cost, spent: false }; + }; + // one of several by its index (#2227), as access.Update keeps them; + // without one, the key's only limit + const ls = body.index === undefined ? [] : k.limit ? [k.limit, ...(k.moreLimits || [])] : []; + const us = body.index === undefined ? [] : k.usedAll || (k.used ? [k.used] : []); + const i = body.index ?? 0; + if (!body.limit) ls.splice(i, 1), us.splice(i, 1); + else ls[i] = body.limit, us[i] = usedOf(body.limit); + k.limit = ls[0]; + k.moreLimits = ls.length > 1 ? ls.slice(1) : undefined; + k.used = us[0]; + k.usedAll = us.length > 1 ? us : undefined; } if (action === "reset-limit-key") { // what it used goes back to 0, tokens and cost together (#1509); - // an N-day or N-hour cycle starts again now, a calendar window keeps its end - const u = k.used, now = Date.now(); - k.used = { ...u, start: new Date(now).toISOString(), calls: 0, tokens: 0, cost: 0, inFlight: 0, unpriced: 0, spent: false, + // an N-day or N-hour cycle starts again now, a calendar window keeps + // its end; one limit of several by its index, or every one (#2227) + const now = Date.now(); + const reset = (u) => ({ ...u, start: new Date(now).toISOString(), calls: 0, tokens: 0, cost: 0, inFlight: 0, unpriced: 0, spent: false, tokensLeft: u.tokenLimit || 0, costLeft: u.costLimit || 0, - reset: u.period === "days" ? new Date(now + u.days * 864e5).toISOString() : u.period === "hours" ? new Date(now + u.hours * 36e5).toISOString() : u.reset }; + reset: u.period === "days" ? new Date(now + u.days * 864e5).toISOString() : u.period === "hours" ? new Date(now + u.hours * 36e5).toISOString() : u.reset }); + if (k.usedAll) k.usedAll = k.usedAll.map((u, i) => (body.index === undefined || body.index === i ? reset(u) : u)), k.used = k.usedAll[0]; + else k.used = reset(k.used); } if (action === "models-key") k.models = body.models?.length ? body.models : undefined; if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined; diff --git a/internal/gui/tests/gateway-key-limits.test.cjs b/internal/gui/tests/gateway-key-limits.test.cjs new file mode 100644 index 000000000..977f39452 --- /dev/null +++ b/internal/gui/tests/gateway-key-limits.test.cjs @@ -0,0 +1,143 @@ +// A gateway key with several limits at once (#2227): the badge says the +// one holding it most and how many more there are, each limit has its +// line under the row, and the editor is of one limit at a time, picked +// from a tab, with Add a limit and Remove this limit. In every language, +// both engines, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const src = fs.readFileSync(path.resolve(__dirname, "../assets/i18n.js"), "utf8"); +const I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")(); + +const hour = 36e5, day = 864e5; +const limits = () => ({ + laptop: { + limit: { period: "hours", hours: 5, cost: 10, since: new Date(Date.now() - 2 * hour).toISOString() }, + moreLimits: [{ period: "week", cost: 50 }], + used: { period: "hours", hours: 5, start: new Date(Date.now() - 2 * hour).toISOString(), reset: new Date(Date.now() + 3 * hour).toISOString(), calls: 8, + tokens: 300000, cost: 4, costLimit: 10, tokensLeft: 0, costLeft: 6, spent: false }, + usedAll: [ + { period: "hours", hours: 5, start: new Date(Date.now() - 2 * hour).toISOString(), reset: new Date(Date.now() + 3 * hour).toISOString(), calls: 8, + tokens: 300000, cost: 4, costLimit: 10, tokensLeft: 0, costLeft: 6, spent: false }, + { period: "week", start: new Date(Date.now() - 4 * day).toISOString(), reset: new Date(Date.now() + 3 * day).toISOString(), calls: 120, + tokens: 9000000, cost: 50.5, costLimit: 50, tokensLeft: 0, costLeft: 0, spent: true }, + ], + }, +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: a key's several limits`, async (t) => { + const tr = (k, vars = {}) => { + const s = lang === "en" ? k : I18N[lang][k]; + assert.equal(typeof s, "string", `${lang} has ${k}`); + return s.replace(/\{(\w+)\}/g, (_, v) => String(vars[v])); + }; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, limits: limits() })); + 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 sent = (action) => events.filter((e) => e.action === action); + const fits = async (what) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, what + " scrolls sideways"); + const fiveHours = tr("every {n} hours", { n: 5 }), week = tr("per week"); + // tap clicks what may be below the fold on a narrow window, after + // scrolling to it with the wheel as a person would, above the footer + const tap = async (loc) => { + await page.mouse.move(width / 2, 400); + for (let i = 0; i < 20 && !(await loc.evaluate((e) => { const r = e.getBoundingClientRect(); return r.top >= 0 && r.bottom <= (document.querySelector("footer.foot")?.getBoundingClientRect().top ?? innerHeight); })); i++) { + await page.mouse.wheel(0, 120); + await page.waitForTimeout(50); + } + await loc.click(); + }; + + // the badge: the spent week holds the key longest, and one more + const badge = row("laptop").locator(".amodels.limit"); + const text = await badge.textContent(); + assert(text.includes(week) && text.includes(tr("Spent")) && text.includes(tr("+1 limit")), "badge says " + text); + assert.equal(await row("laptop").locator(".amodels.limit.spent").count(), 1); + // a line for each, its window first + const lines = row("laptop").locator(".key-limit"); + assert.equal(await lines.count(), 2); + assert((await lines.nth(0).textContent()).startsWith(fiveHours)); + assert((await lines.nth(1).textContent()).startsWith(week)); + assert.equal(await lines.nth(1).evaluate((e) => e.classList.contains("spent")), true); + assert.equal(await row("server").locator(".key-limit").count(), 0, "a key without a limit says nothing"); + await fits("the rows"); + + // the editor opens on the limit holding it, each limit a tab + await badge.click(); + const ed = row("laptop").locator(".key-limit-ed"); + await ed.waitFor(); + const tabs = ed.getByRole("tablist", { name: tr("This key's limits"), exact: true }).getByRole("tab"); + assert.deepEqual((await tabs.allTextContents()).map((s) => s.trim()), [fiveHours, week]); + assert.equal(await tabs.nth(1).getAttribute("aria-selected"), "true"); + const win = ed.getByRole("button", { name: tr("Limit window"), exact: true }); + const costIn = ed.getByRole("textbox", { name: tr("Estimated cost limit, US$"), exact: true }); + assert.equal(await win.getAttribute("data-value"), "week"); + assert.equal(await costIn.inputValue(), "50"); + for (const sel of [".klf-which", ".klf-tab"]) { + assert.equal(await ed.locator(sel).first().evaluate((e) => getComputedStyle(e).borderLeftStyle), "none"); + } + await fits("the editor"); + // Reset usage of the week alone + await tap(ed.getByRole("button", { name: tr("Reset usage"), exact: true })); + const modal = page.locator("#modal"); + await modal.getByRole("button", { name: tr("Reset usage"), exact: true }).click(); + await modal.waitFor({ state: "hidden" }); + assert.deepEqual(sent("reset-limit-key").map((e) => e.body), [{ key: "laptop", index: 1 }]); + assert.equal(await row("laptop").locator(".amodels.limit.spent").count(), 0, "still spent after the week's Reset"); + + // the 5 hours' tab: its own caps, changed alone + await ed.waitFor(); + await ed.getByRole("tab", { name: fiveHours, exact: true }).click(); + assert.equal(await ed.getByRole("tab", { name: fiveHours, exact: true }).getAttribute("aria-selected"), "true"); + assert.equal(await win.getAttribute("data-value"), "hours"); + assert.equal(await costIn.inputValue(), "10"); + await costIn.fill("12"); + // Enter saves, as Save does: on a narrow window Save is below the fold + await costIn.press("Enter"); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").map((e) => e.body), [{ key: "laptop", limit: { period: "hours", hours: 5, tokens: 0, cost: 12, cacheReads: false }, index: 0 }]); + + // Add a limit: a window it has none in, nothing to save until a cap + await badge.click(); + await ed.waitFor(); + await tap(ed.getByRole("button", { name: tr("Add a limit"), exact: true })); + assert.equal(await ed.getByRole("tab", { name: tr("New limit"), exact: true }).getAttribute("aria-selected"), "true"); + assert.equal(await win.getAttribute("data-value"), "day"); + const save = ed.getByRole("button", { name: tr("Save"), exact: true }); + assert.equal(await save.isDisabled(), true, "a limit with no cap can be saved"); + await ed.getByRole("textbox", { name: tr("Token limit"), exact: true }).fill("1000000"); + await tap(save); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").at(-1).body, { key: "laptop", limit: { period: "day", tokens: 1000000, cost: 0, cacheReads: false }, index: 2 }); + assert.equal(await lines.count(), 3); + assert((await badge.textContent()).includes(tr("+{n} limits", { n: 2 }))); + await fits("three limits"); + + // Remove this limit takes off that one only + await badge.click(); + await ed.waitFor(); + await ed.getByRole("tab", { name: tr("per day"), exact: true }).click(); + await tap(ed.getByRole("button", { name: tr("Remove this limit"), exact: true })); + await tap(ed.getByRole("button", { name: tr("Save"), exact: true })); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").at(-1).body, { key: "laptop", limit: null, index: 2 }); + assert.equal(await lines.count(), 2); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/remote_key_limits.go b/internal/provider/remote_key_limits.go index 5c1712502..22863135d 100644 --- a/internal/provider/remote_key_limits.go +++ b/internal/provider/remote_key_limits.go @@ -58,26 +58,30 @@ type GatewayKeyLimit struct { } // remoteKeyAnswer is RemoteKeyLimitPath's answer (budget.Status, as the -// gateway's keyLimit sends it). +// gateway's keyLimit sends it): Limit the one holding the key most, +// Limits each of its limits (#2227), from a magpie that has them. type remoteKeyAnswer struct { - Limited *bool `json:"limited"` - Key string `json:"key"` - Limit *struct { - Period string `json:"period"` - Days int `json:"days"` - Hours int `json:"hours"` - Start time.Time `json:"start"` - Reset time.Time `json:"reset"` - Calls int `json:"calls"` - Tokens int64 `json:"tokens"` - Cost float64 `json:"cost"` - Unpriced int `json:"unpriced"` - TokenLimit int64 `json:"tokenLimit"` - CostLimit float64 `json:"costLimit"` - TokensLeft int64 `json:"tokensLeft"` - CostLeft float64 `json:"costLeft"` - Spent bool `json:"spent"` - } `json:"limit"` + Limited *bool `json:"limited"` + Key string `json:"key"` + Limit *remoteKeyLimit `json:"limit"` + Limits []remoteKeyLimit `json:"limits"` +} + +type remoteKeyLimit struct { + Period string `json:"period"` + Days int `json:"days"` + Hours int `json:"hours"` + Start time.Time `json:"start"` + Reset time.Time `json:"reset"` + Calls int `json:"calls"` + Tokens int64 `json:"tokens"` + Cost float64 `json:"cost"` + Unpriced int `json:"unpriced"` + TokenLimit int64 `json:"tokenLimit"` + CostLimit float64 `json:"costLimit"` + TokensLeft int64 `json:"tokensLeft"` + CostLeft float64 `json:"costLeft"` + Spent bool `json:"spent"` } type remoteKeyRead struct { @@ -170,27 +174,39 @@ func remoteKeyCardOf(ctx context.Context, p Provider, name, key string, fresh bo } // keyLimitCard is what a key's card shows of the remote's answer: a -// window for each cap, named for its period, or one window with no limit. +// window for each cap of each of its limits, named for its period, or one +// window with no limit. What the card says of the key itself is of the +// limit holding it most. func keyLimitCard(a *remoteKeyAnswer) (*GatewayKeyLimit, []QuotaWindow) { l := a.Limit if !*a.Limited || l == nil { return &GatewayKeyLimit{}, []QuotaWindow{{Name: "Limit", Unlimited: true}} } g := &GatewayKeyLimit{Limited: true, Period: l.Period, Days: l.Days, Hours: l.Hours, Start: l.Start, Reset: l.Reset, Calls: l.Calls, Spent: l.Spent, Unpriced: l.Unpriced} - reset := l.Reset + all := a.Limits + if len(all) == 0 { // a magpie from before #2227 tells one + all = []remoteKeyLimit{*l} + } var ws []QuotaWindow share := func(used, limit float64) float64 { return math.Min(100, math.Round(used/limit*1000)/10) } + for _, x := range all { + reset := x.Reset + if x.TokenLimit > 0 { + ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", x.Period), Used: share(float64(x.Tokens), float64(x.TokenLimit)), ResetsAt: &reset, + Amount: float64(x.Tokens), Limit: float64(x.TokenLimit), Unit: "tokens"}) + } + if x.CostLimit > 0 { + ws = append(ws, QuotaWindow{Name: keyWindowName("Spend", x.Period), Used: share(x.Cost, x.CostLimit), ResetsAt: &reset, + Amount: math.Round(x.Cost*100) / 100, Limit: x.CostLimit, Unit: "USD"}) + } + } if l.TokenLimit > 0 { left := l.TokensLeft g.TokensLeft = &left - ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", l.Period), Used: share(float64(l.Tokens), float64(l.TokenLimit)), ResetsAt: &reset, - Amount: float64(l.Tokens), Limit: float64(l.TokenLimit), Unit: "tokens"}) } if l.CostLimit > 0 { left := l.CostLeft g.CostLeft = &left - ws = append(ws, QuotaWindow{Name: keyWindowName("Spend", l.Period), Used: share(l.Cost, l.CostLimit), ResetsAt: &reset, - Amount: math.Round(l.Cost*100) / 100, Limit: l.CostLimit, Unit: "USD"}) } if ws == nil { // limited, with no cap it tells: an answer we can't read return &GatewayKeyLimit{}, []QuotaWindow{{Name: "Limit", Unlimited: true}} diff --git a/internal/provider/remote_key_limits_test.go b/internal/provider/remote_key_limits_test.go new file mode 100644 index 000000000..139ba4afb --- /dev/null +++ b/internal/provider/remote_key_limits_test.go @@ -0,0 +1,19 @@ +package provider + +import ( + "encoding/json" + "testing" +) + +// A magpie from before #2227 answers with "limit" alone: its card is +// that one limit's windows, as before. +func TestKeyLimitCardOneLimit(t *testing.T) { + var a remoteKeyAnswer + if err := json.Unmarshal([]byte(`{"limited":true,"key":"Laptop","limit":{"period":"day","tokens":350,"tokenLimit":1000,"tokensLeft":650,"cost":1.5,"costLimit":5,"costLeft":3.5}}`), &a); err != nil { + t.Fatal(err) + } + g, ws := keyLimitCard(&a) + if !g.Limited || g.Period != "day" || *g.TokensLeft != 650 || *g.CostLeft != 3.5 || len(ws) != 2 || ws[0].Name != "Tokens today" || ws[1].Name != "Spend today" || ws[1].Amount != 1.5 { + t.Fatalf("one limit: %+v %+v", g, ws) + } +}