Files
magpie/internal/gateway/weighted.go
T
yetone 3ec6b4da27 gateway, gui: a provider's keys can be routed by weight, a key weighing 3 taking three requests for every one a key weighing 1 takes (dengtongcai, #841) — Routing already spread requests over a provider's keys in order, in turn, least used first or by pace, but never in a set proportion: two team keys meant to split 75/25 could only go evenly or one after the other. Routing now has By weight (routing "weight") for a provider with keys: each key that's on shows its weight and its share beside it in the editor (Weight 3 · 75%), a click edits it in place and posts keys/weight (provider.SetKeyWeight, 1 to 1000; none or 0 counts as 1, kept out of the file), and providers.json takes it as "weight" on each of keys (keyWeight for the first). The gateway picks as NGINX's smooth weighted round robin does (weighted.go): 3, 1 and 4 go round in every 8 requests in that ratio, never bunched; the others follow in their order for failover. A key resting after a failure is left out of the round while it rests, the others taking its share by their weights, and goes last. A conversation still stays with its key as Stays says (cache-warm across turns by default, within a turn always), and a request kept so is counted against the key that took it, not the one the round picked, so new conversations make up the share; Stays Off gives the ratio request by request. The weight goes with its key through Make first, the editor's Save, backups and WebDAV sync. The Routing page offers By weight for key pools and explains a pick by it; sink (Goes to the back) is off for it as for In turn. zh, ja, de strings. TestWeightedKeys (3:1:4 exact in each of 50 rounds of 8 through perKey and route; with one resting the other two 75/25 and the resting one last; a kept request made up by the next picks) and TestSetKeyWeight fail on the old code (no Weighted); key-weight.test.cjs (WebKit, en and zh: By weight shows the weights and shares, a click sets one and the shares redraw, Smart hides them, no scroll) fails on the old code (no By weight). key-import, panel-routing, routing-save, rate-limited-sink, routing-reset-deadline, account-arrange, gui-ja, gui-de and click-scroll pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-05 08:50:57 +08:00

109 lines
2.9 KiB
Go

package gateway
// Weighted routing (#841): a provider's requests spread over its keys by
// each key's weight, as NGINX's smooth weighted round robin does — keys
// weighing 3 and 1 go a, a, b, a, a, a, b, a…, the ratio held over a
// handful of requests rather than only on average. A key resting after a
// failure is left out of the round while it rests, so the others share
// its requests by their own weights and it takes up its share when it is
// back. A conversation still stays with the key that answered it while
// its affinity says (affinity.go); a request kept so counts against the
// key that took it, not the one the round picked (weightedKept), so new
// conversations make up the share.
import (
"sync"
"github.com/yetone/magpie/internal/provider"
)
// wrr is each weighted provider's round: every key's current weight, and
// the total the last pick was charged.
var wrr = struct {
sync.Mutex
m map[string]*wrrRound // provider id → its round
}{m: map[string]*wrrRound{}}
type wrrRound struct {
cur map[string]int // candidate rest → current weight
total int
}
// keyWeight is a candidate's weight: its key's, 1 when none.
func keyWeight(c candidate) int { return max(c.p.KeyWeight, 1) }
// resting says whether c rests now, as restLast will find.
func resting(c candidate) bool {
if _, ok := restOf(c.restKey()); ok {
return true
}
if c.restID() != c.restKey() {
_, ok := restOf(c.restID())
return ok
}
return false
}
// weightedFirst puts first the key the provider id's round picks now, the
// others after it in their order, for failover.
func weightedFirst(id string, cs []candidate) []candidate {
wrr.Lock()
defer wrr.Unlock()
r := wrr.m[id]
if r == nil {
r = &wrrRound{cur: map[string]int{}}
wrr.m[id] = r
}
// keys no longer on are dropped from the round
on := make(map[string]bool, len(cs))
for _, c := range cs {
on[c.rest] = true
}
for k := range r.cur {
if !on[k] {
delete(r.cur, k)
}
}
best, total := -1, 0
for i, c := range cs {
if resting(c) {
continue
}
w := keyWeight(c)
r.cur[c.rest] += w
total += w
if best < 0 || r.cur[c.rest] > r.cur[cs[best].rest] {
best = i
}
}
if best < 0 {
return cs // all resting: restLast orders them
}
r.cur[cs[best].rest] -= total
r.total = total
if best == 0 {
return cs
}
return append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...)
}
// weightedKept moves the pick of picked's round to kept, when affinity
// keeps a conversation with kept, another key of the same weighted
// provider: the round counts the requests each key really took.
func weightedKept(picked, kept candidate) {
if picked.p.Routing != provider.Weighted || picked.p.ID != kept.p.ID || picked.rest == kept.rest {
return
}
wrr.Lock()
defer wrr.Unlock()
r := wrr.m[picked.p.ID]
if r == nil {
return
}
if _, ok := r.cur[kept.rest]; !ok {
return
}
r.cur[picked.rest] += r.total
r.cur[kept.rest] -= r.total
}