M1: scrape spine — renderer, extractor, orchestrator /scrape, compose, health, render cache
- renderer: Node/Playwright, single browser + pooled contexts with concurrency
cap and FIFO queue, Redis render cache (graceful no-op without Redis)
- extractor: FastAPI + Trafilatura, HTML -> {title, text, metadata}
- orchestrator: /scrape (render -> extract) with per-stage trace, aggregated
/health, structured JSON logging on all services
- docker-compose for orchestrator/renderer/extractor/redis with healthchecks
Verified locally: end-to-end scrape of example.com and Wikipedia; error paths
for unreachable hosts and bad schemes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
55317f3f75
commit
e2b329b2bb
20 changed files with 1534 additions and 0 deletions
85
services/orchestrator/app/pipeline.py
Normal file
85
services/orchestrator/app/pipeline.py
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
"""Pipeline stages and tracing. The orchestrator owns sequencing + degradation."""
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
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:
|
||||
try:
|
||||
resp = await client.post(url, json=payload, timeout=config.STAGE_TIMEOUT_S)
|
||||
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 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) -> dict:
|
||||
"""render -> extract for one URL. Raises StageError on hard failure."""
|
||||
trace = Trace()
|
||||
rendered = await render(client, url, trace)
|
||||
extracted = await extract(client, rendered["html"], rendered.get("final_url") or url, trace)
|
||||
return {
|
||||
"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"),
|
||||
"trace": trace.as_dict(),
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue