provider, gui, gateway: a thousand keys are listed once and read eight at a time (@NetRozee on X)

@NetRozee on X: "when I add a thousand keys for a custom endpoint magpie
just froze or crash by itself".

Cause. The Providers page asked, for each key, what it rests by
(RestKey), and RestKey listed every key on again (KeysOn), which itself
looked along the list for each key: cubic in the keys. /api/providers
and every /api/keys/* answer, an import too, are drawn through it. The
gateway asked, for each key of every request, whether it serves the
model (Serves), and each asking read the provider's lists again (a
filememo stat, and a read while the file is new) and looked along each
model's key ids. fetchPerKey looked along the lists for each key and
model the same way.

Fix.
- KeysOn drops repeats by a set.
- RestKeys finds once whether several keys are on; providerInfo uses it.
- Serving(model) reads the lists once and answers for each key from sets
  (keyLists, made again when the lists are read anew); perKeyBarred and
  the test pick use it. Serves is Serving for one key.
- fetchPerKey keeps each model's keys as a set and indexes the old list
  by key once; a model kept for a failed key is kept once, as before.
- KeysListed and ListsRead count listings and list reads for the tests.
Behaviour is otherwise the same.

Measured (go test in a sandbox HOME, a custom provider, 50 models):
                         1000 keys          5000 keys
  providerInfo           1.54s -> 7.5ms     2m42.9s -> 18.3ms
  providersState         1.65s -> 110ms     2m40.3s -> 146ms
  POST /api/keys/import  1.64s -> 82ms      2m44.7s -> 288ms
  of one more key
  gateway perKey         100.9ms -> 8.2ms   (old not run) -> 40ms
  (each request)

Tests (counts, not time), each red on the old code by hand:
- TestProviderInfoListsKeysOnce: old 1001 listings for 1000 keys, 11 for
  10; new 0 and 0.
- TestPerKeyReadsListsOnce: old 1001 list reads for 1000 keys, 11 for
  10; new 1 and 1.
- TestServingReadsListsOnce, TestRestKeysIsRestKey,
  TestKeysOnDropsRepeats: same answers as before.

And the vendor reads. KeyBalances, PlanQuotas and remoteKeyCards started a goroutine
for each key and asked the vendor with all of them at once: a thousand
keys were a thousand requests to one relay together, each holding a
connection and its body.

Fix. keySlots holds each provider's reads to keyReadsAtOnce (8); other
providers' keys are read beside them. A read whose context is done goes
on without a slot and fails at once, as before.

Tests:
- TestKeyReadsEightAtOnce: a Command Code provider of 31 keys and a
  remote magpie of 31 keys behind a server that holds every request.
  Old code (the slots taken out by hand): 31 at once for balances, plans
  and remote limits; new: 8, every card still there.
- TestKeySlots: a done context takes no slot; another provider's keys
  have their own.

Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on af601541e with this series: 66 packages ok, 18 without tests, no FAIL (gateway 468.5s, provider 215.9s, gui 122.8s).
This commit is contained in:
yetone
2026-10-16 08:43:02 +08:00
parent af601541ef
commit 0bbb2f3ca4
11 changed files with 517 additions and 26 deletions
+2 -1
View File
@@ -232,6 +232,7 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou
return out, nil, left, barred
}
keys := p.KeysOn()
serves := p.Serving(model) // the lists read once, not once a key (@NetRozee on X)
var unlisted []candidate
var noURL provider.Protocol
for i, k := range keys {
@@ -250,7 +251,7 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou
barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i})
continue
}
if !p.Serves(k, model) {
if !serves(k) {
// the vendor lists the model to another key only
unlisted = append(unlisted, candidate{p: q, model: model, rest: rest, rank: i})
continue
+54
View File
@@ -0,0 +1,54 @@
package gateway
import (
"fmt"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// @NetRozee on X: a custom endpoint given a thousand keys froze magpie.
// Every request asked, for each key, whether it serves the model, and
// each asking read the provider's lists again: a thousand reads of the
// lists' file a request. The reads are counted, not timed: a request
// reads them as often with a thousand keys as with ten.
func TestPerKeyReadsListsOnce(t *testing.T) {
fresh(t)
reads := func(n int) int64 {
p := provider.Provider{ID: fmt.Sprintf("relay%d", n), Name: "Relay", Chat: "https://relay.example/v1", Key: "sk-first"}
ids, odd := []string{provider.KeyID(p.Key)}, []string{}
for i := range n {
k := fmt.Sprintf("sk-key-%d-%04d", n, i)
p.Keys = append(p.Keys, provider.KeyAccount{Key: k})
if i%2 == 0 {
ids = append(ids, provider.KeyID(k))
} else {
odd = append(odd, provider.KeyID(k))
}
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(p.ID, p.Chat, []catalog.Model{{ID: "m", Keys: ids}, {ID: "other", Keys: odd}}); err != nil {
t.Fatal(err)
}
q, err := provider.Find(p.ID)
if err != nil {
t.Fatal(err)
}
perKey(*q, "m", provider.Chat) // the lists' first read
before := provider.ListsRead()
cs := perKey(*q, "m", provider.Chat)
// the keys listing m; the others list another model only
if want := 1 + (n+1)/2; len(cs) != want {
t.Errorf("%d keys: %d candidates, want %d", n, len(cs), want)
}
return provider.ListsRead() - before
}
few, many := reads(10), reads(1000)
t.Logf("lists read %d times for 10 keys, %d for 1000", few, many)
if many > few+2 {
t.Errorf("a request read the lists %d times with 1000 keys, %d with 10: once a key", many, few)
}
}
+48
View File
@@ -0,0 +1,48 @@
package gui
import (
"fmt"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// @NetRozee on X: a custom endpoint given a thousand keys froze magpie.
// The Providers page asked, for each key, what it rests by, and that
// listed every key on again: a thousand keys took 1.5s to draw, five
// thousand 2m40s, and each answer of /api/keys/* (an import too) waited
// as long. The listings are counted, not timed: a provider's row lists
// its keys as often with a thousand keys as with ten.
func TestProviderInfoListsKeysOnce(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
lists := func(n int) int64 {
p := provider.Provider{ID: fmt.Sprintf("relay%d", n), Name: "Relay", Chat: "http://127.0.0.1:1/v1", Key: "sk-first"}
for i := range n {
p.Keys = append(p.Keys, provider.KeyAccount{Key: fmt.Sprintf("sk-key-%d-%04d", n, i)})
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
q, err := provider.Find(p.ID)
if err != nil {
t.Fatal(err)
}
providerInfo(*q, nil)
before := provider.KeysListed()
info := providerInfo(*q, nil)
if len(info.KeyList) != n+1 {
t.Errorf("%d keys listed, want %d", len(info.KeyList), n+1)
}
return provider.KeysListed() - before
}
few, many := lists(10), lists(1000)
t.Logf("keys listed %d times for 10 keys, %d for 1000", few, many)
if many > few+2 {
t.Errorf("a provider's row listed its keys %d times with 1000 keys, %d with 10: once a key", many, few)
}
}
+4 -2
View File
@@ -624,12 +624,14 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
out.KeyList = []provider.KeyInfo{}
}
// a key the gateway passes over after a failure says so on its row
restKey := p.RestKeys()
for i, k := range out.KeyList {
if !k.On {
continue
}
if r, ok := keyRestOf(p.RestKey(k)); ok {
out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: p.RestKey(k)}
key := restKey(k)
if r, ok := keyRestOf(key); ok {
out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key}
}
}
if !out.Key.Set && p.Ready() {
+2
View File
@@ -1381,10 +1381,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
jobs = slices.DeleteFunc(jobs, func(j job) bool { return !wantsCard(ctx, j.p.ID, j.user) })
out := make([]SubscriptionQuota, len(jobs))
var wg sync.WaitGroup
var slots keySlots
for i, j := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
defer slots.take(ctx, j.p.ID)()
q := SubscriptionQuota{Provider: j.p.ID, Name: j.p.Name, Icon: j.p.Icon, User: j.user, Windows: []QuotaWindow{}}
if clineKeyCard(j.p) {
// ClinePass's limits beside the credits (cline_usage.go)
+79 -6
View File
@@ -8,12 +8,14 @@ package provider
// else that talks to the vendor reads it as before.
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -58,11 +60,34 @@ type KeyRest struct {
// RestKey is what the gateway rests the key k of a provider by: the
// provider's id while it has one key on, else the id and the key's.
func (p Provider) RestKey(k KeyInfo) string {
if len(p.KeysOn()) > 1 {
return p.ID + "#" + k.ID
func (p Provider) RestKey(k KeyInfo) string { return p.RestKeys()(k) }
// RestKeys is RestKey for each of a provider's keys in turn, whether it
// has more than one on found once: found again for every key, a list of
// a thousand keys was read a thousand times over, and the Providers page
// took seconds to draw it, minutes for five thousand (@NetRozee on X).
func (p Provider) RestKeys() func(KeyInfo) string {
several := p.severalOn()
return func(k KeyInfo) string {
if several {
return p.ID + "#" + k.ID
}
return p.ID
}
return p.ID
}
// severalOn is len(p.KeysOn()) > 1 without listing them: a key on after
// the first that isn't the first again.
func (p Provider) severalOn() bool {
if p.Key == "" {
return false
}
for _, k := range p.Keys {
if !k.Off && k.Key != "" && k.Key != p.Key {
return true
}
}
return false
}
func keyID(key string) string {
@@ -89,18 +114,33 @@ func (p Provider) KeyList() []KeyInfo {
// saved one that's on. A key listed twice — providers.json's "keys"
// naming the first key again, as #1772's did — is one key, asked once.
func (p Provider) KeysOn() []KeyAccount {
keysListed.Add(1)
if p.Key == "" {
return nil
}
out := []KeyAccount{p.first()}
// a set, not a look along the list for each key: the gateway asks
// this for every request, and a thousand keys made it half a million
// looks (@NetRozee on X)
seen := make(map[string]bool, len(p.Keys)+1)
seen[p.Key] = true
for _, k := range p.Keys {
if !k.Off && k.Key != "" && !slices.ContainsFunc(out, func(o KeyAccount) bool { return o.Key == k.Key }) {
if !k.Off && k.Key != "" && !seen[k.Key] {
seen[k.Key] = true
out = append(out, k)
}
}
return out
}
// keysListed counts KeysOn's lists (KeysListed).
var keysListed atomic.Int64
// KeysListed is how many times a provider's keys on have been listed in
// this process: a test counts them, not the time a page or request took,
// to say they are listed once and not once a key (@NetRozee on X).
func KeysListed() int64 { return keysListed.Load() }
// AddKey saves one more key for a provider, on: it takes requests after
// the ones before it. It becomes the first when the provider has none.
func AddKey(id, name, key string, proto Protocol) error {
@@ -221,6 +261,39 @@ func AddKeys(id string, keys []string, proto Protocol) (added, had int, err erro
return added, had, Save(*p)
}
// keyReadsAtOnce is how many of one provider's keys have their balance,
// plan or limits read from the vendor at once. Every key at once was a
// thousand requests to one relay together for a provider of a thousand
// keys (@NetRozee on X); other providers' keys are read beside them.
const keyReadsAtOnce = 8
// keySlots is one read's slots, keyReadsAtOnce for each provider.
type keySlots struct {
sync.Mutex
m map[string]chan struct{}
}
// take waits for a slot of the provider id's, and gives what frees it. A
// read given up on (ctx done) goes on without one, to fail at once.
func (s *keySlots) take(ctx context.Context, id string) (release func()) {
s.Lock()
if s.m == nil {
s.m = map[string]chan struct{}{}
}
c := s.m[id]
if c == nil {
c = make(chan struct{}, keyReadsAtOnce)
s.m[id] = c
}
s.Unlock()
select {
case c <- struct{}{}:
return func() { <-c }
case <-ctx.Done():
return func() {}
}
}
// first is the first key as a KeyAccount, and setFirst makes k the first.
func (p *Provider) first() KeyAccount {
return KeyAccount{Name: p.KeyName, Key: p.Key, Protocol: p.KeyProtocol, Weight: p.KeyWeight}
+234
View File
@@ -0,0 +1,234 @@
package provider
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/agentenv"
"github.com/yetone/magpie/internal/catalog"
)
// @NetRozee on X: a custom endpoint given a thousand keys froze magpie.
// What a page or a request asks of a provider's keys is counted here, not
// timed: each is asked once for all of them, never once a key.
func manyKeys(n int) Provider {
p := Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example/v1", Key: "sk-first"}
for i := range n {
p.Keys = append(p.Keys, KeyAccount{Key: fmt.Sprintf("sk-key-%04d", i)})
}
return p
}
// RestKeys is RestKey, found once: the id alone while one key is on, the
// id and the key's while several are, the first key again or keys off
// not counting.
func TestRestKeysIsRestKey(t *testing.T) {
for _, p := range []Provider{
{ID: "a", Key: "k"},
{ID: "a", Key: "k", Keys: []KeyAccount{{Key: "k"}, {Key: "j", Off: true}, {Key: ""}}},
{ID: "a", Key: "k", Keys: []KeyAccount{{Key: "k"}, {Key: "j"}}},
manyKeys(3),
} {
rest := p.RestKeys()
for _, k := range p.KeyList() {
if got, want := rest(k), p.ID+map[bool]string{true: "#" + k.ID}[len(p.KeysOn()) > 1]; got != want {
t.Errorf("%+v: key %s rests by %q, want %q", p.Keys, k.ID, got, want)
}
}
}
}
// KeysOn still drops a key listed twice, and the first key listed again,
// keeping the order (#1772).
func TestKeysOnDropsRepeats(t *testing.T) {
p := Provider{ID: "a", Key: "k", Keys: []KeyAccount{{Key: "j"}, {Key: "k"}, {Key: "i", Off: true}, {Key: "j"}, {Key: "h"}, {Key: ""}}}
var got []string
for _, k := range p.KeysOn() {
got = append(got, k.Key)
}
if fmt.Sprint(got) != "[k j h]" {
t.Errorf("keys on %v, want [k j h]", got)
}
}
// Whether each of a thousand keys serves a model reads the provider's
// lists once, and answers as Serves did: a key no list names serves
// everything, a listed one what its lists hold.
func TestServingReadsListsOnce(t *testing.T) {
isolateFetchHome(t)
p := manyKeys(1000)
if err := Save(p); err != nil {
t.Fatal(err)
}
var odd, all []string
for i, k := range p.KeysOn() {
if i < 900 { // the last hundred are on no list yet
all = append(all, keyID(k.Key))
if i%2 == 1 {
odd = append(odd, keyID(k.Key))
}
}
}
if err := catalog.SaveLive(p.ID, p.Chat, []catalog.Model{{ID: "both", Keys: all}, {ID: "half", Keys: odd}}); err != nil {
t.Fatal(err)
}
q, err := Find(p.ID)
if err != nil {
t.Fatal(err)
}
before := ListsRead()
serves := q.Serving("half")
if got := ListsRead() - before; got != 1 {
t.Errorf("Serving read the lists %d times, want once", got)
}
n := 0
for i, k := range q.KeysOn() {
want := i >= 900 || i%2 == 1
if serves(k) != want {
t.Fatalf("key %d serves half: %v, want %v", i, !want, want)
}
if q.Serves(k, "half") != want {
t.Fatalf("Serves key %d half: %v, want %v", i, !want, want)
}
n++
}
if n != 1001 {
t.Fatalf("%d keys on", n)
}
}
// heldAtOnce is how many requests the server was asked at once at most
// while call ran: each is held until a ninth comes, or a second passes
// with eight held.
func heldAtOnce(t *testing.T, answer func(w http.ResponseWriter, r *http.Request), call func()) int {
t.Helper()
var mu sync.Mutex
in, most := 0, 0
gate := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
in++
most = max(most, in)
mu.Unlock()
<-gate
answer(w, r)
mu.Lock()
in--
mu.Unlock()
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
defer func() { http.DefaultClient.Transport = old }()
done := make(chan struct{})
go func() { defer close(done); call() }()
var eight time.Time
for open := true; open; {
mu.Lock()
m := most
mu.Unlock()
switch {
case m > keyReadsAtOnce:
open = false
case m == keyReadsAtOnce && eight.IsZero():
eight = time.Now()
case m == keyReadsAtOnce && time.Since(eight) > time.Second:
open = false
}
select {
case <-done:
open = false
case <-time.After(5 * time.Millisecond):
}
}
close(gate)
<-done
t.Logf("%d asked at once at most", most)
return most
}
// A provider's keys have their balances, plans and remote limits read
// eight at a time: every key at once was a thousand requests to one
// relay together.
func TestKeyReadsEightAtOnce(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
forget := func() {
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
ForgetBalances()
forgetPlanQuotas()
}
forget()
t.Cleanup(forget)
p := Provider{ID: "commandcode", Name: "commandCode", Preset: "commandcode", Key: "cmd-first",
Chat: "https://api.commandcode.ai/provider/v1", Anthropic: "https://api.commandcode.ai/provider"}
for i := range 30 {
p.Keys = append(p.Keys, KeyAccount{Key: fmt.Sprintf("cmd-%02d", i)})
}
if err := Save(p); err != nil {
t.Fatal(err)
}
credits := func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/alpha/billing/credits" {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Write([]byte(`{"credits":{"monthlyCredits":1,"purchasedCredits":0,"freeCredits":0}}`))
}
var cards int
most := heldAtOnce(t, credits, func() { cards = len(KeyBalances(context.Background())) })
if most > keyReadsAtOnce || cards != 31 {
t.Errorf("balances: %d cards, %d asked at once, want 31 cards and at most %d", cards, most, keyReadsAtOnce)
}
most = heldAtOnce(t, credits, func() { cards = len(PlanQuotas(context.Background())) })
if most > keyReadsAtOnce {
t.Errorf("plans: %d asked at once, want at most %d", most, keyReadsAtOnce)
}
remote := Provider{ID: "office", Name: "Office", Anthropic: "http://office.example", Key: p.Key, Keys: p.Keys}
most = heldAtOnce(t, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"limited":false}`)) }, func() {
cards = len(remoteKeyCards(context.Background(), remote, true, ""))
})
if most > keyReadsAtOnce || cards != 31 {
t.Errorf("remote limits: %d cards, %d asked at once, want 31 cards and at most %d", cards, most, keyReadsAtOnce)
}
}
// One read given up on goes on without a slot; another provider's keys
// have slots of their own.
func TestKeySlots(t *testing.T) {
var s keySlots
var free []func()
for range keyReadsAtOnce {
free = append(free, s.take(context.Background(), "a"))
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
s.take(ctx, "a")() // returns at once, with nothing to free
if n := len(s.m["a"]); n != keyReadsAtOnce {
t.Fatalf("%d of a's slots taken, want %d", n, keyReadsAtOnce)
}
b := s.take(context.Background(), "b") // never waits on a's
b()
free[0]()
s.take(context.Background(), "a")()
if n := len(s.m["a"]); n != keyReadsAtOnce-1 {
t.Fatalf("%d of a's slots taken, want %d", n, keyReadsAtOnce-1)
}
}
+88 -16
View File
@@ -165,9 +165,18 @@ func (p Provider) lists() bool {
return p.Account != nil || pr == nil || !pr.NoList || strings.TrimSpace(p.ModelsURL) != "" || p.listRegion(pr)
}
// listsRead counts liveAll's reads (ListsRead).
var listsRead atomic.Int64
// ListsRead is how many times a provider's saved lists have been asked
// for whole in this process: a test counts them to say a request reads
// them once, not once a key (@NetRozee on X).
func ListsRead() int64 { return listsRead.Load() }
// liveAll is live with the models that draw or make videos too
// (catalog.LiveAll): which of its keys serves one is said there alone.
func (p Provider) liveAll() ([]catalog.Model, bool) {
listsRead.Add(1)
if !p.lists() {
return nil, false
}
@@ -1151,6 +1160,10 @@ func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalog
}
var deadKept []deadModel
at := map[string]int{}
// each model's keys as a set beside its list, and the models of the
// list before that each key saw: with a thousand keys, looking along
// the lists for every key and model took seconds (@NetRozee on X)
var has []map[string]bool
add := func(m catalog.Model, id string) int {
i, ok := at[m.ID]
if !ok {
@@ -1158,15 +1171,19 @@ func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalog
at[m.ID], i = len(out), len(out)
out = append(out, m)
from = append(from, nil)
has = append(has, map[string]bool{})
} else {
out[i].ImageInput = sharedImageInput(out[i].ImageInput, m.ImageInput)
out[i].Images = out[i].Images && m.Images
}
if !slices.Contains(out[i].Keys, id) {
if !has[i][id] {
has[i][id] = true
out[i].Keys = append(out[i].Keys, id)
}
return i
}
var oldOf map[string][]int // a key's models in old, made when one fails
keptOld := map[int]bool{} // the models of old kept for a key that failed
var base string
var lastErr error
for _, k := range keys {
@@ -1175,9 +1192,23 @@ func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalog
l, err := q.fetchOne(ctx)
if err != nil {
lastErr = err
for _, m := range old {
if slices.Contains(m.Keys, id) {
deadKept = append(deadKept, deadModel{add(m, id), m.Keys})
if oldOf == nil {
oldOf = map[string][]int{}
for j, m := range old {
for _, kid := range m.Keys {
if js := oldOf[kid]; len(js) == 0 || js[len(js)-1] != j {
oldOf[kid] = append(js, j)
}
}
}
}
for _, j := range oldOf[id] {
i := add(old[j], id)
// each model kept once: its bases are worked out from
// its keys, the same whichever of them failed
if !keptOld[j] {
keptOld[j] = true
deadKept = append(deadKept, deadModel{i, old[j].Keys})
}
}
continue
@@ -1308,23 +1339,64 @@ func anyImageInput(a, b *bool) *bool {
// first of five keys left out of every request). The lists are read whole,
// the models that draw or make videos among them: a text key never says
// it serves an image model only another key lists (#1657).
func (p Provider) Serves(k KeyAccount, model string) bool {
live, ok := p.liveAll()
func (p Provider) Serves(k KeyAccount, model string) bool { return p.Serving(model)(k) }
// Serving is Serves for model, for each of the provider's keys in turn:
// the lists are read once, not once a key. Read for every key of every
// request, a provider of a thousand keys had its list's file looked at a
// thousand times, and each model's thousand keys looked along, before a
// request went out: a tenth of a second a request, seconds for five
// thousand keys (@NetRozee on X).
func (p Provider) Serving(model string) func(KeyAccount) bool {
x, ok := p.keyLists()
if !ok {
return true
return func(KeyAccount) bool { return true }
}
id := keyID(k.Key)
var keys []string
found, listed := false, false
keys, found := x.of[model]
return func(k KeyAccount) bool {
id := keyID(k.Key)
return !found || len(keys) == 0 || !x.listed[id] || keys[id]
}
}
// keyLists is which keys the provider's lists name: every key any model
// is listed to, and each model's own, as sets. The last of a model listed
// twice is its.
type keyLists struct {
from []catalog.Model // the lists they were made from
listed map[string]bool
of map[string]map[string]bool
}
// keyListsMade is each provider's keyLists, made again when its lists are
// read anew: a list read once is the same list until its file changes
// (filememo), and is held here, so a new one is never at its address.
var keyListsMade = struct {
sync.Mutex
m map[string]*keyLists
}{m: map[string]*keyLists{}}
func (p Provider) keyLists() (*keyLists, bool) {
live, ok := p.liveAll()
if !ok || len(live) == 0 {
return nil, false
}
keyListsMade.Lock()
defer keyListsMade.Unlock()
if x := keyListsMade.m[p.ID]; x != nil && len(x.from) == len(live) && &x.from[0] == &live[0] {
return x, true
}
x := &keyLists{from: live, listed: map[string]bool{}, of: make(map[string]map[string]bool, len(live))}
for _, m := range live {
if m.ID == model {
keys, found = m.Keys, true
}
if !listed && slices.Contains(m.Keys, id) {
listed = true
set := make(map[string]bool, len(m.Keys))
for _, id := range m.Keys {
set[id] = true
x.listed[id] = true
}
x.of[m.ID] = set
}
return !found || len(keys) == 0 || !listed || slices.Contains(keys, id)
keyListsMade.m[p.ID] = x
return x, true
}
// ServesNone is the user's Select none (NoModels) with nothing picked:
+2
View File
@@ -678,10 +678,12 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
}
got := make([]*SubscriptionQuota, len(jobs))
var wg sync.WaitGroup
var slots keySlots
for i, j := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
defer slots.take(ctx, j.p.ID)()
q := SubscriptionQuota{Provider: j.p.ID, Name: j.p.Name, Icon: j.p.Icon, User: j.user, Windows: []QuotaWindow{}}
plan, ws, team, err := planKeyWindows(j.p.Via(ctx), j.p, j.src, j.key)
// a vendor failing a while (Command Code answers billing/credits
+2
View File
@@ -124,10 +124,12 @@ func remoteKeyCards(ctx context.Context, p Provider, fresh bool, only string) []
names, keys := remoteKeys(p)
out := make([]SubscriptionQuota, len(keys))
var wg sync.WaitGroup
var slots keySlots
for i := range keys {
wg.Add(1)
go func() {
defer wg.Done()
defer slots.take(ctx, p.ID)()
out[i] = remoteKeyCardOf(ctx, p, names[i], keys[i], fresh && (only == "" || only == names[i]))
}()
}
+2 -1
View File
@@ -307,10 +307,11 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
q, ok := p, true
if keys := p.KeysOn(); len(keys) > 0 {
ok = false
serves := p.Serving(model)
pick:
for _, want := range []Protocol{proto, ""} {
for _, k := range keys {
if k.Protocol == want && p.Serves(k, model) {
if k.Protocol == want && serves(k) {
q, ok = p.WithKey(k), true
break pick
}