"""Pipeline stages and tracing. The orchestrator owns sequencing + degradation.""" import asyncio import time from typing import Any import httpx from . import config from .cache import Cache class Trace: """Per-request trace: stage timings, cache hits, degraded stages.""" def __init__(self) -> None: self.stages: list[dict[str, Any]] = [] self.degraded: list[str] = [] def record(self, stage: str, ms: float, *, cache: str | None = None, error: str | None = None) -> None: entry: dict[str, Any] = {"stage": stage, "ms": round(ms, 1)} if cache: entry["cache"] = cache if error: entry["error"] = error self.degraded.append(stage) self.stages.append(entry) def as_dict(self) -> dict: return {"stages": self.stages, "degraded": self.degraded} class StageError(Exception): def __init__(self, stage: str, detail: str): self.stage = stage self.detail = detail super().__init__(f"{stage}: {detail}") async def _post(client: httpx.AsyncClient, url: str, payload: dict, stage: str) -> dict: # One retry on connection-level failures (service restarting, transient net); # timeouts and HTTP errors are not retried — the work itself likely failed. for attempt in range(2): try: resp = await client.post(url, json=payload, timeout=config.STAGE_TIMEOUT_S) break except (httpx.ConnectError, httpx.ConnectTimeout) as exc: if attempt == 1: raise StageError(stage, f"unreachable: {exc}") from exc await asyncio.sleep(0.5) except httpx.HTTPError as exc: raise StageError(stage, f"unreachable: {exc}") from exc if resp.status_code != 200: detail = resp.text[:500] raise StageError(stage, f"HTTP {resp.status_code}: {detail}") 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: start = time.monotonic() try: result = await _post(client, f"{config.RENDERER_URL}/render", {"url": url}, "render") except StageError as exc: trace.record("render", (time.monotonic() - start) * 1000, error=exc.detail) raise trace.record("render", (time.monotonic() - start) * 1000, cache=result.get("cache")) return result async def extract(client: httpx.AsyncClient, html: str, url: str, trace: Trace) -> dict: start = time.monotonic() try: result = await _post(client, f"{config.EXTRACTOR_URL}/extract", {"html": html, "url": url}, "extract") except StageError as exc: trace.record("extract", (time.monotonic() - start) * 1000, error=exc.detail) raise trace.record("extract", (time.monotonic() - start) * 1000, cache=result.get("cache")) return result async def scrape_url(client: httpx.AsyncClient, url: str, cache: Cache | None = None) -> dict: """render -> extract for one URL. Raises StageError on hard failure. The extracted result is cached by URL; a hit skips render entirely. """ trace = Trace() cache_key = f"scrape:{url}" if cache: start = time.monotonic() cached = await cache.get_json(cache_key) if cached: trace.record("scrape_cache", (time.monotonic() - start) * 1000, cache="hit") return {**cached, "trace": trace.as_dict()} rendered = await render(client, url, trace) extracted = await extract(client, rendered["html"], rendered.get("final_url") or url, trace) result = { "url": url, "final_url": rendered.get("final_url"), "status": rendered.get("status"), "title": extracted.get("title"), "content": extracted.get("text", ""), "metadata": extracted.get("metadata", {}), "extractor_used": extracted.get("extractor_used"), "thin": extracted.get("thin", False), } blocked = result["status"] is not None and result["status"] >= 400 if cache and result["content"] and not result["thin"] and not blocked: await cache.set_json(cache_key, result, config.EXTRACT_CACHE_TTL) return {**result, "trace": trace.as_dict()} async def search_contents( client: httpx.AsyncClient, query: str, max_results: int, cache: Cache | None = None ) -> dict: """Tavily-equivalent flow: search, then render+extract the results in parallel. Per-URL failures degrade to a result without content instead of failing the whole request. """ trace = Trace() results = await search(client, query, max_results, trace) start = time.monotonic() scraped = await asyncio.gather( *(scrape_url(client, r["url"], cache) for r in results), return_exceptions=True ) trace.record("contents", (time.monotonic() - start) * 1000) out = [] failed = [] for meta, page in zip(results, scraped): entry = dict(meta) if isinstance(page, StageError): entry.update({"content": None, "error": page.detail}) failed.append(meta["url"]) elif isinstance(page, BaseException): raise page else: entry.update( { "content": page["content"], "title": page.get("title") or meta["title"], "metadata": page.get("metadata", {}), "final_url": page.get("final_url"), "status": page.get("status"), "thin": page.get("thin", False), } ) # Blocked (4xx/5xx) or empty/thin pages are quality failures even # though the render itself "succeeded" — surface them, don't hide them. status = page.get("status") if (status and status >= 400) or page.get("thin") or not page["content"]: failed.append(meta["url"]) out.append(entry) if failed: trace.degraded.append("contents") return {"results": out, "failed_urls": failed, "trace": trace.as_dict()}