SlouchyQuill on Discord asked for a Tavily key pool after dsh-tavily-pool: several keys, each key's quota shown, keys rotated. Before this, the comma-separated keys (#1477) always started from the key that last answered, so one key took every search until it was refused, a refused key kept no rest of its own, and nothing showed what a key had left. What changed: - Turns (internal/gateway/search_keys.go). Searches take turns over the keys by default (round robin, a counter per vendor). pick=order (CLI) or In order (Settings) always starts from the first key; the pick is saved in SearchAPI.Pick. - Rests. A refused key rests: 401/403 for 10m ("turned away"), 402 for 1h ("out of credit"), 429 for its Retry-After held to 30s-10m (1m without one). 432/433 count as out of credit from Tavily only; from any other vendor they rest as a rate limit. A resting key is asked after the others, soonest back first, so failover is kept, and it wakes when it answers. Rests are keyed by a hash of the key. - Quota (internal/gateway/search_quota.go). Each Tavily key's quota is read from GET /usage with that key. The fixture is the documented reply from docs.tavily.com. The key's own limit is used when it has one; otherwise its plan's plan_limit/plan_usage, which the account's keys share. A failed read, or a reply missing those fields, says unknown and why, never 0. A read is kept 2m unless asked fresh. A key found used up with no pay-as-you-go credit rests 1h; a later read with credit wakes it. - Keys never appear in full. The vendor's error has the key masked (tvly-…abcd), and errors name "key N (tvly-…abcd)". - GUI. Settings › Models › Web search adds a "Keys of <API>" row under an API with several keys or with Tavily's: In turn / In order, each key masked with what it has used and why it is asked last, and Check again. There is an API for it (POST /api/settings/search-quota), and 13 strings in zh, zh-TW, ja and de. - CLI. `magpie search` lists the pick and each Tavily key's quota, read fresh; `magpie search add … pick=turns|order`. - Docs. gateway-routing.md has a new section "A search API's keys"; both READMEs have a line on web search. What was run: - go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui: ok. After the last rebase, provider and cli again, and gateway -race -run Search. - New tests: TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin, TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas and TestSearchKeyNeverInFull. Each guarantee was broken by hand and its tests went red: - turns pinned to the first key: RoundRobin and RefusedRests; - rests ignored: TestSearchAPIKeysTakeTurns, RefusedRests and TestSearchQuotas; - key masking removed: NeverInFull; - a failed read reported as known: TestSearchQuotas. - gofmt -l; go vet -tags nogui for darwin, linux and windows on the four packages. - GUI: search-keys.test.cjs covers en, zh, zh-TW, ja and de × Chromium and WebKit × 1100 and 420px: 20/20. Without the new .search-keys .val wrap rule, de at 420px fails ("Erneut prüfen" went past the window's edge). - search-api, search-first, search-instead, search-mcp, searcher-pick, settings-search, provider-search, gui-de, gui-ja and i18n-keys: 56/56 in each engine. - Full suite in Chromium (concurrency 6, load ~40): 4498/4504. The files that failed (gateway-key-groups, rest-try-now, routing-wb-restricted, text-size, usage-sum-whole) were rerun alone. All pass except usage-sum-whole, which fails now and then on an origin/main worktree too under the same load (#1864, #2023; rest-try-now and routing-wb-restricted are #1905). None of them touch search. - Real Tavily API with two invalid keys: /search returns 401 {"detail":{"error":"Unauthorized: missing or invalid API key."}}, which counts as a refusal. Both keys rest 10m as turned away, the error names them only masked, and both quotas read "unknown · 401". Checked through a test and through the nogui CLI binary in a sandbox HOME. Not tried: a valid key's /usage against the real API. No Tavily key was at hand, so the quota parsing is checked against the documented bytes only.
142 lines
4.7 KiB
Go
142 lines
4.7 KiB
Go
package gateway
|
|
|
|
import (
|
|
"cmp"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"net/http"
|
|
"slices"
|
|
"strconv"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// A search API given several keys (#1477) spreads its searches over them
|
|
// (SlouchyQuill on Discord, after dsh-tavily-pool): each search starts
|
|
// from the next key, or from the first when the API is set to use them in
|
|
// order (provider.SearchPickOrder). A key the API refused lately, or one a
|
|
// quota read found used up, rests: it is asked only after every key that
|
|
// isn't resting, the one whose rest ends first before the others, so a
|
|
// search still has every key to fall back on.
|
|
|
|
// keyRest is why a key rests, and until when.
|
|
type keyRest struct {
|
|
Until time.Time
|
|
Why string // "turned away", "out of credit", "rate limited", "used up"
|
|
}
|
|
|
|
var (
|
|
// searchRests is, by searchKeyID, the keyRest of each key resting
|
|
searchRests sync.Map
|
|
// searchTurns is, by vendor, how many searches have taken a turn: the
|
|
// key the next one starts from
|
|
searchTurns sync.Map
|
|
)
|
|
|
|
// searchKeyID is how a key is known here: its vendor and a hash, so no
|
|
// map, log or dump holds the key itself.
|
|
func searchKeyID(vendor, key string) string {
|
|
sum := sha256.Sum256([]byte(key))
|
|
return vendor + " " + hex.EncodeToString(sum[:8])
|
|
}
|
|
|
|
// The rests a refusal earns. A rate limit says when to come back
|
|
// (Retry-After), held between its bounds; a key turned away (401/403) may
|
|
// be fixed by the user, so it is tried again in a few minutes; one out of
|
|
// credit gets its credit back no sooner than a top-up, so it rests longer.
|
|
const (
|
|
rateLimitRest = time.Minute
|
|
rateLimitRestMin = 30 * time.Second
|
|
rateLimitRestMax = 10 * time.Minute
|
|
turnedAwayRest = 10 * time.Minute
|
|
outOfCreditRest = time.Hour
|
|
)
|
|
|
|
// searchRestFor is how long a key a search API refused with this status rests,
|
|
// and why. 432 and 433 are Tavily's own (its plan's and its pay-as-you-go
|
|
// limit), out of credit there; from any other API they are only a refusal,
|
|
// and rest as a rate limit does.
|
|
func searchRestFor(vendor string, status int, retryAfter string, now time.Time) (time.Duration, string) {
|
|
switch {
|
|
case status == 401 || status == 403:
|
|
return turnedAwayRest, "turned away"
|
|
case status == 402, vendor == "tavily" && (status == 432 || status == 433):
|
|
return outOfCreditRest, "out of credit"
|
|
}
|
|
d := rateLimitRest
|
|
if s, err := strconv.Atoi(retryAfter); err == nil && s >= 0 {
|
|
d = time.Duration(s) * time.Second
|
|
} else if at, err := http.ParseTime(retryAfter); err == nil {
|
|
d = at.Sub(now)
|
|
}
|
|
return min(max(d, rateLimitRestMin), rateLimitRestMax), "rate limited"
|
|
}
|
|
|
|
// restSearchKey sets a key resting for d; a rest it has that ends later
|
|
// is kept.
|
|
func restSearchKey(vendor, key string, d time.Duration, why string, now time.Time) {
|
|
r := keyRest{Until: now.Add(d), Why: why}
|
|
if was, ok := searchKeyRest(vendor, key, now); ok && was.Until.After(r.Until) {
|
|
return
|
|
}
|
|
searchRests.Store(searchKeyID(vendor, key), r)
|
|
}
|
|
|
|
// wakeSearchKey ends a key's rest: it answered, or a quota read found it
|
|
// has credit.
|
|
func wakeSearchKey(vendor, key string) { searchRests.Delete(searchKeyID(vendor, key)) }
|
|
|
|
// searchKeyRest is the rest a key is in now, if it is.
|
|
func searchKeyRest(vendor, key string, now time.Time) (keyRest, bool) {
|
|
v, ok := searchRests.Load(searchKeyID(vendor, key))
|
|
if !ok {
|
|
return keyRest{}, false
|
|
}
|
|
r := v.(keyRest)
|
|
if !now.Before(r.Until) {
|
|
return keyRest{}, false
|
|
}
|
|
return r, true
|
|
}
|
|
|
|
// searchKeyOrder is the order a search asks a's keys in, by their index:
|
|
// from the key whose turn it is (the first, for SearchPickOrder), each
|
|
// key resting put after those that aren't, the soonest awake first.
|
|
// Taking turns, each call moves the next search on by one.
|
|
func searchKeyOrder(a provider.SearchAPI, keys []string, now time.Time) []int {
|
|
n := len(keys)
|
|
start := 0
|
|
if a.Pick != provider.SearchPickOrder && n > 1 {
|
|
v, _ := searchTurns.LoadOrStore(a.Vendor, new(atomic.Uint64))
|
|
start = int((v.(*atomic.Uint64).Add(1) - 1) % uint64(n))
|
|
}
|
|
order := make([]int, 0, n)
|
|
var resting []int
|
|
until := map[int]time.Time{}
|
|
for k := range n {
|
|
i := (start + k) % n
|
|
if r, ok := searchKeyRest(a.Vendor, keys[i], now); ok {
|
|
resting, until[i] = append(resting, i), r.Until
|
|
continue
|
|
}
|
|
order = append(order, i)
|
|
}
|
|
slices.SortStableFunc(resting, func(x, y int) int { return until[x].Compare(until[y]) })
|
|
return append(order, resting...)
|
|
}
|
|
|
|
// forgetSearchKeys forgets every rest and turn: a test's fresh start.
|
|
func forgetSearchKeys() {
|
|
searchRests.Clear()
|
|
searchTurns.Clear()
|
|
}
|
|
|
|
// keyLabel is how an error names one of several keys: its place in the
|
|
// list and the key masked.
|
|
func keyLabel(i int, key string) string {
|
|
return "key " + strconv.Itoa(i+1) + " (" + cmp.Or(provider.MaskSearchKey(key), "none") + ")"
|
|
}
|