"""Query SearXNG instances (failover mode), normalize + dedup results.""" import logging from urllib.parse import urlsplit, urlunsplit import httpx log = logging.getLogger("searcher") class SearchError(Exception): pass def _canonical(url: str) -> str: """Dedup key: scheme+host+path, ignoring query/fragment noise-insensitive cases.""" parts = urlsplit(url) return urlunsplit((parts.scheme.lower(), parts.netloc.lower(), parts.path.rstrip("/"), parts.query, "")) def normalize(raw_results: list[dict], instance_name: str, max_results: int) -> list[dict]: seen: set[str] = set() results = [] for item in raw_results: url = item.get("url") if not url or not url.startswith(("http://", "https://")): continue key = _canonical(url) if key in seen: continue seen.add(key) results.append( { "url": url, "title": (item.get("title") or "").strip(), "snippet": (item.get("content") or "").strip(), "rank": len(results) + 1, "source_instance": instance_name, } ) if len(results) >= max_results: break return results async def search_failover( client: httpx.AsyncClient, instances: list[dict], query: str, max_results: int, timeout_s: float ) -> list[dict]: """Try instances in order; first instance with non-empty results wins. An instance that answers 200 with an empty result set is treated as a soft failure (its upstream engines are likely rate-limited) and we fall through to the next instance. Only if *every* instance is empty do we return []; we raise SearchError only when every instance hard-fails (unreachable/non-200/ non-JSON). """ if not instances: raise SearchError("no SearXNG instances configured") errors = [] any_responded = False for inst in instances: try: resp = await client.get( f"{inst['url']}/search", params={"q": query, "format": "json"}, timeout=timeout_s, ) if resp.status_code != 200: raise SearchError(f"HTTP {resp.status_code}") raw = resp.json().get("results", []) except (httpx.HTTPError, SearchError, ValueError) as exc: log.warning("instance %s failed: %s", inst["name"], exc) errors.append(f"{inst['name']}: {exc}") continue any_responded = True results = normalize(raw, inst["name"], max_results) if results: return results log.warning("instance %s returned 0 results; trying next", inst["name"]) if any_responded: # Every instance that answered came back empty — a real "no results" # (or all upstreams rate-limited), not a hard failure. return [] raise SearchError("; ".join(errors))