"""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"}