Files
magpie/internal/gateway/search_api_keys_test.go
T
yetone a5d72a095b gateway, gui, cli: a search API's keys take turns, a refused one rests, and each Tavily key shows what it has used (SlouchyQuill)
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.
2026-10-14 08:24:03 +08:00

90 lines
3.1 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A search API given several keys (#1477) goes on to the next when one is
// out of credit (Tavily's 432), and the next search doesn't start from the
// keys refused, which rest (search_pool_test.go). A failure that isn't about the key (a 500) doesn't spend
// the other keys.
func TestSearchAPIKeysTakeTurns(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var mu sync.Mutex
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
mu.Lock()
asked = append(asked, key)
mu.Unlock()
switch key {
case "tvly-spent":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(432)
io.WriteString(w, `{"detail":{"error":"This request exceeds your plan's set usage limit. Please upgrade your plan or contact support@tavily.com"}}`)
case "tvly-down":
http.Error(w, `{"detail":{"error":"down"}}`, 500)
case "tvly-good":
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1","score":0.9}]}`)
default:
http.Error(w, `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`, 401)
}
}))
defer srv.Close()
s := New()
search := func(keys string) (string, error) {
t.Helper()
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: keys, URL: srv.URL}); err != nil {
t.Fatal(err)
}
mu.Lock()
asked = nil
mu.Unlock()
said, _, err := s.apiSearch(context.Background(), "latest go")
return said, err
}
took := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(asked) }
forgetSearchKeys()
if said, err := search("tvly-spent, tvly-bad\ntvly-good"); err != nil || !strings.Contains(said, "go1.27.1") {
t.Fatalf("spent, bad, good: %q, %v", said, err)
}
if got := took(); !slices.Equal(got, []string{"tvly-spent", "tvly-bad", "tvly-good"}) {
t.Errorf("asked with %v, want each key in turn", got)
}
if _, err := search("tvly-spent,tvly-bad,tvly-good"); err != nil {
t.Fatal(err)
}
if got := took(); !slices.Equal(got, []string{"tvly-good"}) {
t.Errorf("the next search asked with %v, want the key that answered, the others resting", got)
}
forgetSearchKeys()
if _, err := search("tvly-down,tvly-good"); err == nil {
t.Error("a 500 on the first key went on to the next")
}
if got := took(); !slices.Equal(got, []string{"tvly-down"}) {
t.Errorf("asked with %v after a 500, want the first key alone", got)
}
forgetSearchKeys()
_, err := search("tvly-spent,tvly-bad")
if err == nil || !strings.Contains(err.Error(), "key 1 (") || !strings.Contains(err.Error(), "usage limit") || !strings.Contains(err.Error(), "key 2 (") {
t.Errorf("every key refused: %v", err)
}
if as := provider.StoredSearchAPIs(); len(as) != 1 || as[0].Key != "tvly-spent,tvly-bad" || as[0].MaskedKey() != "tvly…pent, ••••••••" {
t.Errorf("stored %+v, shown %q", as, as[0].MaskedKey())
}
}