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:
parent
56e7fa16dd
commit
53f0d50e7a
10 changed files with 298 additions and 1 deletions
6
config/instances.yml
Normal file
6
config/instances.yml
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# SearXNG instance pool. MVP: one local instance; add more entries later for
|
||||||
|
# rotation/fan-out (the searcher already reads the whole list for failover).
|
||||||
|
instances:
|
||||||
|
- name: local
|
||||||
|
url: http://searxng:8080
|
||||||
|
weight: 1
|
||||||
|
|
@ -10,6 +10,7 @@ services:
|
||||||
REDIS_URL: redis://redis:6379
|
REDIS_URL: redis://redis:6379
|
||||||
EXTRACT_CACHE_TTL: ${EXTRACT_CACHE_TTL:-3600}
|
EXTRACT_CACHE_TTL: ${EXTRACT_CACHE_TTL:-3600}
|
||||||
depends_on:
|
depends_on:
|
||||||
|
- searcher
|
||||||
- renderer
|
- renderer
|
||||||
- extractor
|
- extractor
|
||||||
- redis
|
- redis
|
||||||
|
|
@ -19,6 +20,31 @@ services:
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 3
|
retries: 3
|
||||||
|
|
||||||
|
searcher:
|
||||||
|
build: services/searcher
|
||||||
|
environment:
|
||||||
|
REDIS_URL: redis://redis:6379
|
||||||
|
SEARCH_CACHE_TTL: ${SEARCH_CACHE_TTL:-300}
|
||||||
|
INSTANCES_FILE: /config/instances.yml
|
||||||
|
volumes:
|
||||||
|
- ./config:/config:ro
|
||||||
|
depends_on:
|
||||||
|
- searxng
|
||||||
|
- redis
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
searxng:
|
||||||
|
image: searxng/searxng:latest
|
||||||
|
environment:
|
||||||
|
SEARXNG_SECRET: ${SEARXNG_SECRET:-change-me-lwss-internal}
|
||||||
|
SEARXNG_BASE_URL: http://searxng:8080/
|
||||||
|
volumes:
|
||||||
|
- ./searxng:/etc/searxng:ro
|
||||||
|
|
||||||
renderer:
|
renderer:
|
||||||
build: services/renderer
|
build: services/renderer
|
||||||
environment:
|
environment:
|
||||||
|
|
|
||||||
16
searxng/settings.yml
Normal file
16
searxng/settings.yml
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
# SearXNG settings for the LWSS-internal instance.
|
||||||
|
# JSON format must be enabled for the searcher; limiter disabled (internal only).
|
||||||
|
use_default_settings: true
|
||||||
|
|
||||||
|
# secret_key comes from the SEARXNG_SECRET env var (set in compose).
|
||||||
|
server:
|
||||||
|
limiter: false
|
||||||
|
image_proxy: false
|
||||||
|
|
||||||
|
search:
|
||||||
|
formats:
|
||||||
|
- html
|
||||||
|
- json
|
||||||
|
|
||||||
|
ui:
|
||||||
|
static_use_hash: true
|
||||||
|
|
@ -29,12 +29,21 @@ class ScrapeRequest(BaseModel):
|
||||||
url: str
|
url: str
|
||||||
|
|
||||||
|
|
||||||
|
class SearchRequest(BaseModel):
|
||||||
|
query: str
|
||||||
|
max_results: int = 10
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
async def health() -> dict:
|
async def health() -> dict:
|
||||||
"""Aggregate health across all downstream services."""
|
"""Aggregate health across all downstream services."""
|
||||||
client: httpx.AsyncClient = app.state.client
|
client: httpx.AsyncClient = app.state.client
|
||||||
services = {}
|
services = {}
|
||||||
for name, base in [("renderer", config.RENDERER_URL), ("extractor", config.EXTRACTOR_URL)]:
|
for name, base in [
|
||||||
|
("searcher", config.SEARCHER_URL),
|
||||||
|
("renderer", config.RENDERER_URL),
|
||||||
|
("extractor", config.EXTRACTOR_URL),
|
||||||
|
]:
|
||||||
try:
|
try:
|
||||||
resp = await client.get(f"{base}/health", timeout=5)
|
resp = await client.get(f"{base}/health", timeout=5)
|
||||||
services[name] = resp.json() if resp.status_code == 200 else {"status": "error"}
|
services[name] = resp.json() if resp.status_code == 200 else {"status": "error"}
|
||||||
|
|
@ -49,6 +58,17 @@ async def health() -> dict:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/search")
|
||||||
|
async def search(req: SearchRequest) -> dict:
|
||||||
|
trace = pipeline.Trace()
|
||||||
|
try:
|
||||||
|
results = await pipeline.search(app.state.client, req.query, req.max_results, trace)
|
||||||
|
except pipeline.StageError as exc:
|
||||||
|
log.error("search failed: %s", exc.detail)
|
||||||
|
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc
|
||||||
|
return {"results": results, "trace": trace.as_dict()}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/scrape")
|
@app.post("/scrape")
|
||||||
async def scrape(req: ScrapeRequest) -> dict:
|
async def scrape(req: ScrapeRequest) -> dict:
|
||||||
if not req.url.startswith(("http://", "https://")):
|
if not req.url.startswith(("http://", "https://")):
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,19 @@ async def _post(client: httpx.AsyncClient, url: str, payload: dict, stage: str)
|
||||||
return resp.json()
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def search(client: httpx.AsyncClient, query: str, max_results: int, trace: Trace) -> list[dict]:
|
||||||
|
start = time.monotonic()
|
||||||
|
try:
|
||||||
|
result = await _post(
|
||||||
|
client, f"{config.SEARCHER_URL}/search", {"query": query, "max_results": max_results}, "search"
|
||||||
|
)
|
||||||
|
except StageError as exc:
|
||||||
|
trace.record("search", (time.monotonic() - start) * 1000, error=exc.detail)
|
||||||
|
raise
|
||||||
|
trace.record("search", (time.monotonic() - start) * 1000, cache=result.get("cache"))
|
||||||
|
return result.get("results", [])
|
||||||
|
|
||||||
|
|
||||||
async def render(client: httpx.AsyncClient, url: str, trace: Trace) -> dict:
|
async def render(client: httpx.AsyncClient, url: str, trace: Trace) -> dict:
|
||||||
start = time.monotonic()
|
start = time.monotonic()
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
11
services/searcher/Dockerfile
Normal file
11
services/searcher/Dockerfile
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY app ./app
|
||||||
|
|
||||||
|
ENV PORT=8001
|
||||||
|
EXPOSE 8001
|
||||||
|
CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"]
|
||||||
30
services/searcher/app/instances.py
Normal file
30
services/searcher/app/instances.py
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
"""File-based SearXNG instance list.
|
||||||
|
|
||||||
|
Re-read (mtime-checked) on every access so hand edits apply without restart.
|
||||||
|
MVP runs failover over this list; fan-out/rotation reuse the same source later.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
INSTANCES_FILE = os.environ.get("INSTANCES_FILE", "/config/instances.yml")
|
||||||
|
|
||||||
|
_cache: dict = {"mtime": None, "instances": []}
|
||||||
|
|
||||||
|
|
||||||
|
def load_instances() -> list[dict]:
|
||||||
|
try:
|
||||||
|
mtime = os.path.getmtime(INSTANCES_FILE)
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
if _cache["mtime"] != mtime:
|
||||||
|
with open(INSTANCES_FILE) as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
_cache["instances"] = [
|
||||||
|
{"name": i.get("name", i["url"]), "url": i["url"].rstrip("/"), "weight": i.get("weight", 1)}
|
||||||
|
for i in data.get("instances", [])
|
||||||
|
if i.get("url")
|
||||||
|
]
|
||||||
|
_cache["mtime"] = mtime
|
||||||
|
return _cache["instances"]
|
||||||
103
services/searcher/app/main.py
Normal file
103
services/searcher/app/main.py
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
"""Searcher: SearXNG pool front-end with normalization, dedup, and caching."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import redis.asyncio as aioredis
|
||||||
|
from fastapi import FastAPI, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from .instances import load_instances
|
||||||
|
from .search import SearchError, search_failover
|
||||||
|
|
||||||
|
SEARCH_CACHE_TTL = int(os.environ.get("SEARCH_CACHE_TTL", "300"))
|
||||||
|
SEARCH_TIMEOUT_S = float(os.environ.get("SEARCH_TIMEOUT_S", "15"))
|
||||||
|
REDIS_URL = os.environ.get("REDIS_URL", "")
|
||||||
|
|
||||||
|
|
||||||
|
class JsonFormatter(logging.Formatter):
|
||||||
|
def format(self, record: logging.LogRecord) -> str:
|
||||||
|
return json.dumps(
|
||||||
|
{
|
||||||
|
"ts": self.formatTime(record),
|
||||||
|
"level": record.levelname.lower(),
|
||||||
|
"service": "searcher",
|
||||||
|
"msg": record.getMessage(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
handler = logging.StreamHandler(sys.stdout)
|
||||||
|
handler.setFormatter(JsonFormatter())
|
||||||
|
logging.basicConfig(level=logging.INFO, handlers=[handler])
|
||||||
|
log = logging.getLogger("searcher")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
app.state.client = httpx.AsyncClient()
|
||||||
|
app.state.redis = aioredis.from_url(REDIS_URL, socket_timeout=2) if REDIS_URL else None
|
||||||
|
yield
|
||||||
|
if app.state.redis:
|
||||||
|
await app.state.redis.aclose()
|
||||||
|
await app.state.client.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="LWSS Searcher", lifespan=lifespan)
|
||||||
|
|
||||||
|
|
||||||
|
class SearchRequest(BaseModel):
|
||||||
|
query: str
|
||||||
|
max_results: int = 10
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
async def health() -> dict:
|
||||||
|
redis_ok = False
|
||||||
|
if app.state.redis:
|
||||||
|
try:
|
||||||
|
redis_ok = await app.state.redis.ping()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"service": "searcher",
|
||||||
|
"instances": [i["name"] for i in load_instances()],
|
||||||
|
"redis": redis_ok,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/search")
|
||||||
|
async def search(req: SearchRequest) -> dict:
|
||||||
|
if not req.query.strip():
|
||||||
|
raise HTTPException(status_code=400, detail="query must be non-empty")
|
||||||
|
|
||||||
|
cache_key = "search:" + hashlib.sha256(f"{req.query}:{req.max_results}".encode()).hexdigest()
|
||||||
|
if app.state.redis:
|
||||||
|
try:
|
||||||
|
hit = await app.state.redis.get(cache_key)
|
||||||
|
if hit:
|
||||||
|
return {"results": json.loads(hit), "cache": "hit"}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
results = await search_failover(
|
||||||
|
app.state.client, load_instances(), req.query, req.max_results, SEARCH_TIMEOUT_S
|
||||||
|
)
|
||||||
|
except SearchError as exc:
|
||||||
|
log.error("search failed: %s", exc)
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
if app.state.redis and results:
|
||||||
|
try:
|
||||||
|
await app.state.redis.set(cache_key, json.dumps(results), ex=SEARCH_CACHE_TTL)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
log.info("search %r -> %d results", req.query, len(results))
|
||||||
|
return {"results": results, "cache": "miss"}
|
||||||
67
services/searcher/app/search.py
Normal file
67
services/searcher/app/search.py
Normal 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))
|
||||||
5
services/searcher/requirements.txt
Normal file
5
services/searcher/requirements.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
fastapi>=0.115
|
||||||
|
uvicorn[standard]>=0.32
|
||||||
|
httpx>=0.27
|
||||||
|
redis>=5.0
|
||||||
|
pyyaml>=6.0
|
||||||
Loading…
Add table
Add a link
Reference in a new issue