"""Orchestrator: the only externally exposed service (REST now, MCP in M4).""" from contextlib import asynccontextmanager import httpx from fastapi import FastAPI, HTTPException from pydantic import BaseModel from . import config, pipeline from .auth import BearerAuthMiddleware from .cache import Cache from .logging_setup import setup from .mcp_server import mcp, runtime log = setup() @asynccontextmanager async def lifespan(app: FastAPI): app.state.client = httpx.AsyncClient() app.state.cache = Cache(config.REDIS_URL) runtime["client"] = app.state.client runtime["cache"] = app.state.cache async with mcp.session_manager.run(): yield await app.state.cache.close() await app.state.client.aclose() app = FastAPI(title="LWSS Orchestrator", lifespan=lifespan) app.add_middleware(BearerAuthMiddleware, api_key=config.API_KEY) app.mount("/mcp", mcp.streamable_http_app()) class ScrapeRequest(BaseModel): url: str class SearchRequest(BaseModel): query: str max_results: int = 10 @app.get("/health") async def health() -> dict: """Aggregate health across all downstream services.""" client: httpx.AsyncClient = app.state.client services = {} for name, base in [ ("searcher", config.SEARCHER_URL), ("renderer", config.RENDERER_URL), ("extractor", config.EXTRACTOR_URL), ]: try: resp = await client.get(f"{base}/health", timeout=5) services[name] = resp.json() if resp.status_code == 200 else {"status": "error"} except httpx.HTTPError: services[name] = {"status": "unreachable"} overall = "ok" if all(s.get("status") == "ok" for s in services.values()) else "degraded" return { "status": overall, "service": "orchestrator", "redis": await app.state.cache.is_ready(), "services": services, } @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("/search/contents") async def search_contents(req: SearchRequest) -> dict: try: data = await pipeline.search_contents(app.state.client, req.query, req.max_results, app.state.cache) except pipeline.StageError as exc: log.error("search/contents failed at %s: %s", exc.stage, exc.detail) raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc log.info( "search/contents %r -> %d results (%d failed)", req.query, len(data["results"]), len(data["failed_urls"]), ) return data @app.post("/scrape") async def scrape(req: ScrapeRequest) -> dict: if not req.url.startswith(("http://", "https://")): raise HTTPException(status_code=400, detail="url must be http(s)") try: result = await pipeline.scrape_url(app.state.client, req.url, app.state.cache) except pipeline.StageError as exc: log.error("scrape failed at %s: %s", exc.stage, exc.detail) raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc log.info("scraped %s (%d chars)", req.url, len(result["content"])) return result