M3: search — SearXNG container, searcher service, orchestrator /search

- searcher: file-based instance list (mtime-reloaded, hand-editable), failover
  across instances, URL normalization + dedup, Redis search cache (300s TTL)
- searxng: pinned settings.yml with JSON format enabled and limiter disabled,
  secret from SEARXNG_SECRET env; wired into compose with config volume
- orchestrator: /search proxying the searcher with per-stage trace; searcher
  included in aggregated /health

Verified against a mock SearXNG: failover past a dead instance, dedup of
trailing-slash duplicates, non-http URL filtering, cache miss/hit flags.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
User 2026-07-05 22:07:10 -07:00
parent 56e7fa16dd
commit 53f0d50e7a
10 changed files with 298 additions and 1 deletions

View file

@ -0,0 +1,67 @@
"""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 success wins. Raises SearchError if all fail."""
if not instances:
raise SearchError("no SearXNG instances configured")
errors = []
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", [])
return normalize(raw, inst["name"], max_results)
except (httpx.HTTPError, SearchError, ValueError) as exc:
log.warning("instance %s failed: %s", inst["name"], exc)
errors.append(f"{inst['name']}: {exc}")
raise SearchError("; ".join(errors))