| 1 | package websearch_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ecdsa" |
| 7 | "crypto/elliptic" |
| 8 | "crypto/rand" |
| 9 | "crypto/tls" |
| 10 | "crypto/x509" |
| 11 | "crypto/x509/pkix" |
| 12 | "encoding/json" |
| 13 | "errors" |
| 14 | "fmt" |
| 15 | "io" |
| 16 | "log/slog" |
| 17 | "math/big" |
| 18 | "net/http" |
| 19 | "net/http/httptest" |
| 20 | "net/netip" |
| 21 | "os" |
| 22 | "path/filepath" |
| 23 | "strings" |
| 24 | "sync" |
| 25 | "testing" |
| 26 | "time" |
| 27 | |
| 28 | "amadan.net/oficina/equipo/internal/websearch" |
| 29 | "amadan.net/oficina/equipo/internal/websearch/websearchtest" |
| 30 | "amadan.net/oficina/equipo/internal/websource/guard" |
| 31 | "amadan.net/rastrillo/rastrillo/budget" |
| 32 | "amadan.net/rastrillo/rastrillo/db" |
| 33 | ) |
| 34 | |
| 35 | func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| 36 | |
| 37 | const sentinel = "SENTINEL-KEY-0123456789" |
| 38 | |
| 39 | type ready struct{} |
| 40 | |
| 41 | func (ready) Ready(context.Context) error { return nil } |
| 42 | func (ready) Inside(netip.Addr) bool { return false } |
| 43 | |
| 44 | // vendor is a TLS server answering as kagi.com, www.mojeek.com and |
| 45 | // api.search.brave.com, recording each request. |
| 46 | type vendor struct { |
| 47 | srv *httptest.Server |
| 48 | roots *x509.CertPool |
| 49 | mu sync.Mutex |
| 50 | got []*http.Request |
| 51 | body [][]byte |
| 52 | reply func(r *http.Request) (int, []byte) |
| 53 | logs bytes.Buffer |
| 54 | } |
| 55 | |
| 56 | func newVendor(t *testing.T) *vendor { |
| 57 | t.Helper() |
| 58 | key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 59 | if err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "vendor"}, DNSNames: []string{"kagi.com", "www.mojeek.com", "api.search.brave.com", "other.example.org"}, |
| 63 | NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true} |
| 64 | der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | cert, _ := x509.ParseCertificate(der) |
| 69 | v := &vendor{roots: x509.NewCertPool()} |
| 70 | v.roots.AddCert(cert) |
| 71 | v.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 72 | raw, _ := io.ReadAll(r.Body) |
| 73 | v.mu.Lock() |
| 74 | v.got = append(v.got, r) |
| 75 | v.body = append(v.body, raw) |
| 76 | reply := v.reply |
| 77 | v.mu.Unlock() |
| 78 | status, body := 200, []byte(`{}`) |
| 79 | if reply != nil { |
| 80 | status, body = reply(r) |
| 81 | } |
| 82 | w.Header().Set("Content-Type", "application/json") |
| 83 | if status >= 300 && status < 400 { |
| 84 | w.Header().Set("Location", "https://other.example.org/elsewhere") |
| 85 | } |
| 86 | w.WriteHeader(status) |
| 87 | _, _ = w.Write(body) |
| 88 | })) |
| 89 | v.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} |
| 90 | v.srv.StartTLS() |
| 91 | t.Cleanup(v.srv.Close) |
| 92 | return v |
| 93 | } |
| 94 | |
| 95 | func (v *vendor) guard() guard.Config { |
| 96 | return guard.Config{Inventory: ready{}, Logger: slog.New(slog.NewTextHandler(&v.logs, nil)), |
| 97 | Resolve: func(context.Context, string) ([]netip.Addr, error) { |
| 98 | return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil |
| 99 | }, |
| 100 | TestDial: func(string) (string, *x509.CertPool) { return v.srv.Listener.Addr().String(), v.roots }} |
| 101 | } |
| 102 | |
| 103 | func (v *vendor) requests() ([]*http.Request, [][]byte) { |
| 104 | v.mu.Lock() |
| 105 | defer v.mu.Unlock() |
| 106 | return append([]*http.Request(nil), v.got...), append([][]byte(nil), v.body...) |
| 107 | } |
| 108 | |
| 109 | func fixture(t *testing.T, name string) []byte { |
| 110 | t.Helper() |
| 111 | raw, err := os.ReadFile(filepath.Join("testdata", name+".json")) |
| 112 | if err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | return raw |
| 116 | } |
| 117 | |
| 118 | func answering(v *vendor, status int, body []byte) { |
| 119 | v.mu.Lock() |
| 120 | v.reply = func(*http.Request) (int, []byte) { return status, body } |
| 121 | v.mu.Unlock() |
| 122 | } |
| 123 | |
| 124 | func newBackend(t *testing.T, name string, v *vendor) websearch.Searcher { |
| 125 | t.Helper() |
| 126 | build := map[string]func(string, guard.Config) (websearch.Searcher, error){websearch.Kagi: websearch.NewKagi, websearch.Mojeek: websearch.NewMojeek, websearch.Brave: websearch.NewBrave}[name] |
| 127 | s, err := build(sentinel, v.guard()) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | return s |
| 132 | } |
| 133 | |
| 134 | func class(err error) string { |
| 135 | var e *websearch.Error |
| 136 | if errors.As(err, &e) { |
| 137 | return e.Class |
| 138 | } |
| 139 | return fmt.Sprintf("not a websearch error: %v", err) |
| 140 | } |
| 141 | |
| 142 | // Kagi: a POST to /api/v1/search with the key as a bearer and a body of |
| 143 | // only query and limit; url, title, snippet and time map to a result; |
| 144 | // direct_answer, infobox and weather are ignored; an http result is |
| 145 | // dropped. |
| 146 | func TestKagiParsesFixture(t *testing.T) { |
| 147 | v := newVendor(t) |
| 148 | answering(v, 200, fixture(t, "kagi_ok")) |
| 149 | got, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "dublin weather", 8) |
| 150 | if err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | want := []websearch.Result{ |
| 154 | {Title: "Dublin forecast - Met Éireann", URL: "https://www.met.ie/forecasts/dublin", Snippet: "Rain at first, clearing later. Highs of 11°C.", Date: "2026-11-28T06:00:00Z"}, |
| 155 | {Title: "Dublin - BBC Weather", URL: "https://www.bbc.com/weather/2964574", Snippet: "Light rain and a gentle breeze."}, |
| 156 | } |
| 157 | if fmt.Sprint(got) != fmt.Sprint(want) { |
| 158 | t.Errorf("results %+v", got) |
| 159 | } |
| 160 | reqs, bodies := v.requests() |
| 161 | if len(reqs) != 1 || reqs[0].Method != http.MethodPost || reqs[0].URL.Path != "/api/v1/search" || reqs[0].Host != "kagi.com" || reqs[0].Header.Get("Authorization") != "Bearer "+sentinel || reqs[0].Header.Get("Content-Type") != "application/json" { |
| 162 | t.Fatalf("request %+v", reqs) |
| 163 | } |
| 164 | var body map[string]any |
| 165 | if err := json.Unmarshal(bodies[0], &body); err != nil || len(body) != 2 || body["query"] != "dublin weather" || body["limit"] != float64(8) { |
| 166 | t.Errorf("body %s", bodies[0]) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | func TestKagi400IsBadResponse(t *testing.T) { |
| 171 | v := newVendor(t) |
| 172 | answering(v, 400, fixture(t, "kagi_400")) |
| 173 | if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassBadResponse { |
| 174 | t.Errorf("400: %v", err) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func TestKagi429IsLimit(t *testing.T) { |
| 179 | v := newVendor(t) |
| 180 | answering(v, 429, fixture(t, "kagi_429")) |
| 181 | if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| 182 | t.Errorf("429: %v", err) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func TestKagi401IsAuth(t *testing.T) { |
| 187 | v := newVendor(t) |
| 188 | for _, status := range []int{401, 403} { |
| 189 | answering(v, status, []byte(`{"meta":{},"data":null,"error":[{"code":"auth","url":"x"}]}`)) |
| 190 | if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassAuth { |
| 191 | t.Errorf("%d: %v", status, err) |
| 192 | } |
| 193 | } |
| 194 | answering(v, 503, nil) |
| 195 | if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassUnavailable { |
| 196 | t.Errorf("503: %v", err) |
| 197 | } |
| 198 | answering(v, 302, nil) |
| 199 | if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassBadResponse { |
| 200 | t.Errorf("302: %v", err) |
| 201 | } |
| 202 | if reqs, _ := v.requests(); len(reqs) != 4 { |
| 203 | t.Errorf("a redirect was followed: %d requests", len(reqs)) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | func TestKagiEmptyIsNoResults(t *testing.T) { |
| 208 | v := newVendor(t) |
| 209 | answering(v, 200, fixture(t, "kagi_empty")) |
| 210 | got, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8) |
| 211 | if err != nil || len(got) != 0 { |
| 212 | t.Errorf("empty: %+v %v", got, err) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func TestMojeekParsesFixture(t *testing.T) { |
| 217 | v := newVendor(t) |
| 218 | answering(v, 200, fixture(t, "mojeek_ok")) |
| 219 | got, err := newBackend(t, websearch.Mojeek, v).Search(context.Background(), "dublin weather", 8) |
| 220 | if err != nil || len(got) != 1 || got[0].URL != "https://www.met.ie/forecasts/dublin" || got[0].Snippet != "Rain at first." { |
| 221 | t.Fatalf("results %+v %v", got, err) |
| 222 | } |
| 223 | reqs, _ := v.requests() |
| 224 | q := reqs[0].URL.Query() |
| 225 | if reqs[0].Host != "www.mojeek.com" || q.Get("api_key") != sentinel || q.Get("q") != "dublin weather" || q.Get("fmt") != "json" { |
| 226 | t.Errorf("request %s", reqs[0].URL) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func TestMojeekStatusErrorIsLimit(t *testing.T) { |
| 231 | v := newVendor(t) |
| 232 | answering(v, 200, fixture(t, "mojeek_limit")) |
| 233 | if _, err := newBackend(t, websearch.Mojeek, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| 234 | t.Errorf("daily limit: %v", err) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | func TestBraveParsesFixture(t *testing.T) { |
| 239 | v := newVendor(t) |
| 240 | answering(v, 200, fixture(t, "brave_ok")) |
| 241 | got, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "dublin weather", 8) |
| 242 | if err != nil || len(got) != 1 || got[0].Date != "2 hours ago" { |
| 243 | t.Fatalf("results %+v %v", got, err) |
| 244 | } |
| 245 | reqs, _ := v.requests() |
| 246 | if reqs[0].Host != "api.search.brave.com" || reqs[0].Header.Get("X-Subscription-Token") != sentinel || reqs[0].URL.Query().Get("q") != "dublin weather" { |
| 247 | t.Errorf("request %+v", reqs[0]) |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func TestBrave429IsLimit(t *testing.T) { |
| 252 | v := newVendor(t) |
| 253 | answering(v, 429, fixture(t, "brave_429")) |
| 254 | if _, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| 255 | t.Errorf("429: %v", err) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func TestBrave401IsAuth(t *testing.T) { |
| 260 | v := newVendor(t) |
| 261 | answering(v, 401, nil) |
| 262 | if _, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassAuth { |
| 263 | t.Errorf("401: %v", err) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // Every failure, every log line and every request outside the vendor's |
| 268 | // own origin are free of the key. |
| 269 | func TestSearchErrorsNeverCarryKey(t *testing.T) { |
| 270 | v := newVendor(t) |
| 271 | for _, name := range []string{websearch.Kagi, websearch.Mojeek, websearch.Brave} { |
| 272 | for _, status := range []int{302, 400, 401, 429, 500} { |
| 273 | answering(v, status, []byte(`{"error":"`+sentinel+`"}`)) |
| 274 | _, err := newBackend(t, name, v).Search(context.Background(), "q", 8) |
| 275 | if err == nil || strings.Contains(err.Error(), sentinel) || strings.Contains(fmt.Sprintf("%v %+v %#v", err, err, err), sentinel) { |
| 276 | t.Errorf("%s %d: %v", name, status, err) |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | if strings.Contains(v.logs.String(), sentinel) { |
| 281 | t.Error("a log line holds the key") |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // What goes out is the query, the count and the key: nothing else. |
| 286 | func TestNoPersonDataInSearchRequest(t *testing.T) { |
| 287 | v := newVendor(t) |
| 288 | answering(v, 200, fixture(t, "kagi_empty")) |
| 289 | for _, name := range []string{websearch.Kagi, websearch.Mojeek, websearch.Brave} { |
| 290 | _, _ = newBackend(t, name, v).Search(context.Background(), "dublin weather", 8) |
| 291 | } |
| 292 | reqs, bodies := v.requests() |
| 293 | allowed := map[string]bool{"User-Agent": true, "Accept": true, "Accept-Encoding": true, "Content-Type": true, "Content-Length": true, "Connection": true, "Authorization": true, "X-Subscription-Token": true} |
| 294 | for i, r := range reqs { |
| 295 | for k := range r.Header { |
| 296 | if !allowed[k] { |
| 297 | t.Errorf("%s sent header %s", r.Host, k) |
| 298 | } |
| 299 | } |
| 300 | if r.Header.Get("Cookie") != "" || r.Header.Get("Referer") != "" { |
| 301 | t.Errorf("%s sent a cookie or referer", r.Host) |
| 302 | } |
| 303 | for k := range r.URL.Query() { |
| 304 | if !map[string]bool{"q": true, "fmt": true, "t": true, "date": true, "api_key": true, "count": true}[k] { |
| 305 | t.Errorf("%s sent parameter %s", r.Host, k) |
| 306 | } |
| 307 | } |
| 308 | if len(bodies[i]) > 0 && r.Host != "kagi.com" { |
| 309 | t.Errorf("%s got a body", r.Host) |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | func fakes() (*websearchtest.Fake, *websearchtest.Fake, *websearchtest.MemUsage) { |
| 315 | return &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{}}, &websearchtest.Fake{Backend: "mojeek", Results: map[string][]websearch.Result{}}, |
| 316 | &websearchtest.MemUsage{Caps: map[string]int{"kagi": 10, "mojeek": 10}, Month: "2026-11"} |
| 317 | } |
| 318 | |
| 319 | var hit = []websearch.Result{{Title: "Dublin", URL: "https://www.met.ie/"}} |
| 320 | |
| 321 | func TestChainFallsBackOnError(t *testing.T) { |
| 322 | p, f, u := fakes() |
| 323 | p.Fail = map[string]*websearch.Error{"q": {Class: websearch.ClassUnavailable}} |
| 324 | f.Results["q"] = hit |
| 325 | got, backend, err := websearch.Chain{Primary: p, Fallback: f, Usage: u}.Search(context.Background(), "q", 8, nil) |
| 326 | if err != nil || backend != "mojeek" || len(got) != 1 || p.Asked() != 1 || f.Asked() != 1 { |
| 327 | t.Errorf("%+v %q %v", got, backend, err) |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | func TestChainFallsBackOnEmpty(t *testing.T) { |
| 332 | p, f, u := fakes() |
| 333 | f.Results["q"] = hit |
| 334 | got, backend, err := websearch.Chain{Primary: p, Fallback: f, Usage: u}.Search(context.Background(), "q", 8, nil) |
| 335 | if err != nil || backend != "mojeek" || len(got) != 1 { |
| 336 | t.Errorf("%+v %q %v", got, backend, err) |
| 337 | } |
| 338 | f.Results["q"] = nil |
| 339 | if got, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || len(got) != 0 { |
| 340 | t.Errorf("nothing anywhere: %+v %v", got, err) |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | func TestChainFallsBackOnCap(t *testing.T) { |
| 345 | p, f, u := fakes() |
| 346 | u.Caps["kagi"] = 0 |
| 347 | f.Results["q"] = hit |
| 348 | if _, backend, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || backend != "mojeek" || p.Asked() != 0 { |
| 349 | t.Errorf("%q %v", backend, err) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | func TestChainNoFallbackConfigured(t *testing.T) { |
| 354 | p, _, u := fakes() |
| 355 | p.Fail = map[string]*websearch.Error{"q": {Class: websearch.ClassAuth}} |
| 356 | if _, _, err := (websearch.Chain{Primary: p, Usage: u}).Search(context.Background(), "q", 8, nil); class(err) != websearch.ClassAuth { |
| 357 | t.Errorf("%v", err) |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | func TestChainBothCapsSpentIsLimit(t *testing.T) { |
| 362 | p, f, u := fakes() |
| 363 | u.Caps = map[string]int{} |
| 364 | if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); class(err) != websearch.ClassLimit || p.Asked()+f.Asked() != 0 { |
| 365 | t.Errorf("%v", err) |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | // before runs once per backend; its refusal for the fallback means no |
| 370 | // fallback request and no reservation for it. |
| 371 | func TestBeforeRunsForEachBackend(t *testing.T) { |
| 372 | p, f, u := fakes() |
| 373 | f.Results["q"] = hit |
| 374 | var asked []string |
| 375 | before := func(_ context.Context, backend string) error { |
| 376 | asked = append(asked, backend) |
| 377 | if backend == "mojeek" { |
| 378 | return errors.New("web off") |
| 379 | } |
| 380 | return nil |
| 381 | } |
| 382 | if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, before); err == nil || err.Error() != "web off" { |
| 383 | t.Fatalf("%v", err) |
| 384 | } |
| 385 | if strings.Join(asked, ",") != "kagi,mojeek" || f.Asked() != 0 || u.Used[websearch.Reservation{Backend: "mojeek", Month: "2026-11"}] != 0 { |
| 386 | t.Errorf("asked %v, fallback %d, reserved %v", asked, f.Asked(), u.Used) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | // Each request sent holds one reservation: the primary spent, one |
| 391 | // fallback request and one reservation; a refused before, none; a |
| 392 | // refusal at the final check returns its reservation. |
| 393 | func TestCapReservedOncePerRequest(t *testing.T) { |
| 394 | p, f, u := fakes() |
| 395 | u.Caps["kagi"] = 0 |
| 396 | f.Results["q"] = hit |
| 397 | if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || u.Taken != 1 || f.Asked() != 1 { |
| 398 | t.Fatalf("%v taken %d", err, u.Taken) |
| 399 | } |
| 400 | p, f, u = fakes() |
| 401 | if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, func(context.Context, string) error { return errors.New("off") }); err == nil || u.Taken != 0 { |
| 402 | t.Errorf("refused before: %v taken %d", err, u.Taken) |
| 403 | } |
| 404 | p, f, u = fakes() |
| 405 | p.Hook = func(context.Context, string) error { return errors.New("refused at the final check") } |
| 406 | if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err == nil || f.Asked() != 0 || u.Used[websearch.Reservation{Backend: "kagi", Month: "2026-11"}] != 0 { |
| 407 | t.Errorf("final refusal: %v, fallback %d, used %v", err, f.Asked(), u.Used) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // usageDB is a database with the usage table. |
| 412 | func usageDB(t *testing.T) *db.DB { |
| 413 | t.Helper() |
| 414 | d, err := db.Open(filepath.Join(t.TempDir(), "usage.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 415 | if err != nil { |
| 416 | t.Fatal(err) |
| 417 | } |
| 418 | t.Cleanup(func() { _ = d.Close() }) |
| 419 | if err := d.G.Exec("CREATE TABLE chat_web_search_usage (backend text, month text, used integer, PRIMARY KEY (backend, month))").Error; err != nil { |
| 420 | t.Fatal(err) |
| 421 | } |
| 422 | return d |
| 423 | } |
| 424 | |
| 425 | func TestMonthlyCapResetsByUTCMonth(t *testing.T) { |
| 426 | d := usageDB(t) |
| 427 | now := time.Date(2026, 11, 30, 23, 0, 0, 0, time.UTC) |
| 428 | u := websearch.DBUsage{DB: d.G, Caps: map[string]int{"kagi": 2}, Now: func() time.Time { return now }} |
| 429 | ctx := context.Background() |
| 430 | for i, want := range []bool{true, true, false} { |
| 431 | if _, ok, err := u.Take(ctx, "kagi"); err != nil || ok != want { |
| 432 | t.Errorf("take %d: %v %v", i, ok, err) |
| 433 | } |
| 434 | } |
| 435 | now = time.Date(2026, 12, 1, 0, 0, 1, 0, time.UTC) |
| 436 | if _, ok, err := u.Take(ctx, "kagi"); err != nil || !ok { |
| 437 | t.Errorf("a new month: %v %v", ok, err) |
| 438 | } |
| 439 | if _, ok, _ := u.Take(ctx, "brave"); ok { |
| 440 | t.Error("a backend with no cap took one") |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // A reservation taken just before midnight at the month's end and |
| 445 | // refused after it refunds the old month; concurrent takes in both |
| 446 | // months are counted right. |
| 447 | func TestReturnRefundsItsOwnMonth(t *testing.T) { |
| 448 | d := usageDB(t) |
| 449 | var mu sync.Mutex |
| 450 | now := time.Date(2026, 11, 30, 23, 59, 59, 0, time.UTC) |
| 451 | clock := func() time.Time { mu.Lock(); defer mu.Unlock(); return now } |
| 452 | u := websearch.DBUsage{DB: d.G, Caps: map[string]int{"kagi": 100}, Now: clock} |
| 453 | ctx := context.Background() |
| 454 | r, ok, err := u.Take(ctx, "kagi") |
| 455 | if err != nil || !ok || r.Month != "2026-11" { |
| 456 | t.Fatal(r, ok, err) |
| 457 | } |
| 458 | mu.Lock() |
| 459 | now = time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) |
| 460 | mu.Unlock() |
| 461 | var wg sync.WaitGroup |
| 462 | for range 5 { |
| 463 | wg.Add(1) |
| 464 | go func() { defer wg.Done(); _, _, _ = u.Take(ctx, "kagi") }() |
| 465 | } |
| 466 | wg.Wait() |
| 467 | if err := u.Return(ctx, r); err != nil { |
| 468 | t.Fatal(err) |
| 469 | } |
| 470 | used := map[string]int{} |
| 471 | rows, err := d.G.Raw("SELECT month, used FROM chat_web_search_usage WHERE backend = 'kagi'").Rows() |
| 472 | if err != nil { |
| 473 | t.Fatal(err) |
| 474 | } |
| 475 | defer rows.Close() |
| 476 | for rows.Next() { |
| 477 | var m string |
| 478 | var n int |
| 479 | _ = rows.Scan(&m, &n) |
| 480 | used[m] = n |
| 481 | } |
| 482 | if used["2026-11"] != 0 || used["2026-12"] != 5 { |
| 483 | t.Errorf("used %v", used) |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | func TestBackendSwapByConfig(t *testing.T) { |
| 488 | env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } |
| 489 | c := websearch.ParseConfig(env(nil)) |
| 490 | if c.Primary != "kagi" || c.Fallback != "" { |
| 491 | t.Errorf("defaults %+v", c) |
| 492 | } |
| 493 | v := newVendor(t) |
| 494 | c = websearch.ParseConfig(env(map[string]string{"EQUIPO_WEB_SEARCH": "brave", "EQUIPO_BRAVE_KEY": sentinel, "EQUIPO_BRAVE_MONTHLY_CAP": "500"})) |
| 495 | chain, ok, err := websearch.FromConfig(c, v.guard(), &websearchtest.MemUsage{}) |
| 496 | if err != nil || !ok || chain.Primary.Name() != "brave" || chain.Fallback != nil { |
| 497 | t.Errorf("brave only: %+v %v %v", chain, ok, err) |
| 498 | } |
| 499 | c = websearch.ParseConfig(env(map[string]string{"EQUIPO_KAGI_KEY": sentinel, "EQUIPO_KAGI_MONTHLY_CAP": "1000", "EQUIPO_WEB_SEARCH_FALLBACK": "mojeek", "EQUIPO_MOJEEK_KEY": "m", "EQUIPO_MOJEEK_MONTHLY_CAP": "10"})) |
| 500 | chain, ok, err = websearch.FromConfig(c, v.guard(), &websearchtest.MemUsage{}) |
| 501 | if err != nil || !ok || chain.Primary.Name() != "kagi" || chain.Fallback == nil || chain.Fallback.Name() != "mojeek" { |
| 502 | t.Errorf("kagi then mojeek: %+v %v %v", chain, ok, err) |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | // A backend named without a key or a cap is left out, its name logged, |
| 507 | // never its value. |
| 508 | func TestMisconfiguredBackendLeftOut(t *testing.T) { |
| 509 | v := newVendor(t) |
| 510 | env := map[string]string{"EQUIPO_KAGI_KEY": sentinel, "EQUIPO_KAGI_MONTHLY_CAP": "0"} |
| 511 | _, ok, err := websearch.FromConfig(websearch.ParseConfig(func(k string) string { return env[k] }), v.guard(), &websearchtest.MemUsage{}) |
| 512 | if err != nil || ok { |
| 513 | t.Errorf("no cap: %v %v", ok, err) |
| 514 | } |
| 515 | if !strings.Contains(v.logs.String(), "web_search.misconfigured") || !strings.Contains(v.logs.String(), "backend=kagi") || strings.Contains(v.logs.String(), sentinel) { |
| 516 | t.Errorf("log %q", v.logs.String()) |
| 517 | } |
| 518 | env = map[string]string{"EQUIPO_KAGI_MONTHLY_CAP": "10"} |
| 519 | if _, ok, _ := websearch.FromConfig(websearch.ParseConfig(func(k string) string { return env[k] }), v.guard(), &websearchtest.MemUsage{}); ok { |
| 520 | t.Error("no key: usable") |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | // A request refused before it was sent (the inventory unconfirmed) uses |
| 525 | // no quota; one refused at the final check on a lookup that has ended is |
| 526 | // refunded all the same (Astra phase 3 round 1, P2). |
| 527 | func TestUnsentSearchesRefunded(t *testing.T) { |
| 528 | v := newVendor(t) |
| 529 | g := v.guard() |
| 530 | g.Inventory = notReady{} |
| 531 | s, err := websearch.NewKagi(sentinel, g) |
| 532 | if err != nil { |
| 533 | t.Fatal(err) |
| 534 | } |
| 535 | u := &websearchtest.MemUsage{Caps: map[string]int{"kagi": 5}, Month: "2026-11"} |
| 536 | if _, _, err := (websearch.Chain{Primary: s, Usage: u}).Search(context.Background(), "q", 8, nil); err == nil { |
| 537 | t.Fatal("searched with the inventory unconfirmed") |
| 538 | } |
| 539 | if u.Used[websearch.Reservation{Backend: "kagi", Month: "2026-11"}] != 0 { |
| 540 | t.Errorf("an unsent request used quota: %v", u.Used) |
| 541 | } |
| 542 | // DNS failing, and a connection refused before anything is written: |
| 543 | // nothing went out, nothing is used (round 2, P2). |
| 544 | for name, broken := range map[string]func(*guard.Config){ |
| 545 | "dns": func(g *guard.Config) { |
| 546 | g.Resolve = func(context.Context, string) ([]netip.Addr, error) { return nil, errors.New("no such host") } |
| 547 | }, |
| 548 | "connect": func(g *guard.Config) { |
| 549 | g.TestDial = func(string) (string, *x509.CertPool) { return "127.0.0.1:1", v.roots } |
| 550 | }, |
| 551 | } { |
| 552 | g := v.guard() |
| 553 | broken(&g) |
| 554 | s, err := websearch.NewKagi(sentinel, g) |
| 555 | if err != nil { |
| 556 | t.Fatal(err) |
| 557 | } |
| 558 | if _, _, err := (websearch.Chain{Primary: s, Usage: u}).Search(context.Background(), "q", 8, nil); err == nil || u.Used[websearch.Reservation{Backend: "kagi", Month: "2026-11"}] != 0 { |
| 559 | t.Errorf("%s: %v, used %v", name, err, u.Used) |
| 560 | } |
| 561 | } |
| 562 | p, _, _ := fakes() |
| 563 | ctx, cancel := context.WithCancel(context.Background()) |
| 564 | p.Hook = func(context.Context, string) error { cancel(); return context.Canceled } |
| 565 | if _, _, err := (websearch.Chain{Primary: p, Usage: u}).Search(ctx, "q", 8, nil); err == nil || u.Used[websearch.Reservation{Backend: "kagi", Month: "2026-11"}] != 0 { |
| 566 | t.Errorf("%v, used %v", err, u.Used) |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | type notReady struct{} |
| 571 | |
| 572 | func (notReady) Ready(context.Context) error { return guard.ErrInventoryUnconfirmed } |
| 573 | func (notReady) Inside(netip.Addr) bool { return false } |
| 574 | |