diff --git a/docs/reference.md b/docs/reference.md index 7d71f39d5..8721f96c6 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1726,6 +1726,18 @@ only with a gateway key. A key held to a budget, to some models or to some accounts is told its own calls alone: `/v1/magpie/usage` refuses it with a 403, and `/v1/magpie/usage/requests` keeps only its rows and filter lists. +What is in flight now, for a status bar such as SketchyBar (#2132): +`GET /v1/magpie/concurrency` answers `requests`, every agent request the +gateway is working on, whether or not any limit is set (those waiting for a +slot among them); `waiting`, how many of those wait for a slot under a +provider's or account's limit; and `tools`, Claude Code turns run through a +Claude subscription that wait on their caller's tool results, which are not +requests. Each is `0` when idle. `data` is each limited key's or account's +own count, empty when no limit is set. The read asks no vendor and isn't +counted itself, so it can be polled every second. It answers as +`/v1/magpie/quotas` does: this machine, another only with a gateway key, +and never a held key. + An app that calls its vendor itself, not through magpie, can report those calls so the Usage page counts them: `POST /v1/magpie/usage/requests` with `Content-Type: application/json`. The body is one record or an array of up diff --git a/internal/gateway/busy_test.go b/internal/gateway/busy_test.go index e143bb391..99f45abfe 100644 --- a/internal/gateway/busy_test.go +++ b/internal/gateway/busy_test.go @@ -1,6 +1,7 @@ package gateway import ( + "encoding/json" "io" "net/http" "net/http/httptest" @@ -86,3 +87,103 @@ func TestBusy(t *testing.T) { t.Fatalf("a run ended: %+v", b) } } + +// /v1/magpie/concurrency tells the whole gateway's requests in flight with +// no limit set anywhere (#2132, a status bar polling it): 0 when idle, +// never left out, the poll itself not counted, and the requests waiting +// for a slot counted among them and told apart. +func TestConcurrencyTellsTheWholeGateway(t *testing.T) { + fresh(t) + var hold sync.WaitGroup + started, release := make(chan struct{}, 4), make(chan struct{}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hel"}}]}`+"\n\n") + w.(http.Flusher).Flush() + started <- struct{}{} + <-release + io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + defer up.Close() + one := 1 + if err := provider.Save(provider.Provider{ID: "free", Name: "Free", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "one", Name: "One", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}, MaxConcurrency: &one}); err != nil { + t.Fatal(err) + } + s := New() + gw := httptest.NewServer(s.Handler()) + defer gw.Close() + let := sync.OnceFunc(func() { close(release) }) + defer hold.Wait() + defer let() + + read := func() map[string]any { + t.Helper() + res, err := http.Get(gw.URL + "/v1/magpie/concurrency") + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var out map[string]any + if err := json.NewDecoder(res.Body).Decode(&out); err != nil || res.StatusCode != 200 { + t.Fatalf("concurrency: %d %v", res.StatusCode, err) + } + return out + } + want := func(when string, requests, waiting float64) { + t.Helper() + out := read() + for k, v := range map[string]float64{"requests": requests, "waiting": waiting, "tools": 0} { + if got, ok := out[k].(float64); !ok || got != v { + t.Fatalf("%s: %s = %v, want %v (%v)", when, k, out[k], v, out) + } + } + } + want("idle", 0, 0) + + send := func(model string) { + hold.Add(1) + go func() { + defer hold.Done() + res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"`+model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + if err == nil { + io.Copy(io.Discard, res.Body) + res.Body.Close() + } + }() + } + // one with no limit anywhere, as the reporter's gateway has + send("free/m") + <-started + want("one request, no limit", 1, 0) + + // two on a provider of one slot: one out, one waiting + send("one/m") + <-started + send("one/m") + deadline := time.Now().Add(5 * time.Second) + waiting := func() (n int) { + for _, ln := range s.Lanes() { + n += ln.Waiting + } + return n + } + for waiting() != 1 { + if time.Now().After(deadline) { + t.Fatalf("the second never waited: %v", s.Lanes()) + } + time.Sleep(10 * time.Millisecond) + } + want("three in flight, one waiting", 3, 1) + + let() + hold.Wait() + deadline = time.Now().Add(5 * time.Second) + for s.Busy().Requests != 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + want("done", 0, 0) +} diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index c9c9e6332..86258436a 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -233,7 +233,13 @@ type Lane struct { // concurrency tells each key's or account's Lane. It names the accounts, // so it answers as quotas does: this machine, or one with the key of the -// gateway shared on the local network. +// gateway shared on the local network. Beside them it tells the whole +// gateway's count, limit or none (#2132, for a status bar): requests is +// every agent request in flight, the ones waiting for a slot among them +// (Busy.Requests, a GET like this one never counted), waiting is how many +// of those wait for a slot, and tools the Claude Code turns waiting on +// their caller's tool results, which are not requests. Each is 0 when +// idle, never left out. func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) { if !local(r) && !sharedWith(r) { writeError(w, provider.Chat, http.StatusForbidden, "magpie's concurrency is told to another machine only when magpie is shared on the local network and the request carries its API key") @@ -242,7 +248,13 @@ func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) { if refuseHeld(w, r, heldRefused) { return } - writeJSON(w, 200, map[string]any{"object": "concurrency", "data": s.Lanes()}) + lanes := s.Lanes() + waiting := 0 + for _, ln := range lanes { + waiting += ln.Waiting + } + b := s.Busy() + writeJSON(w, 200, map[string]any{"object": "concurrency", "data": lanes, "requests": b.Requests, "waiting": waiting, "tools": b.Tools}) } // Lanes is how each key or account with requests out or waiting under a