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:
User 2026-07-05 22:02:38 -07:00
parent 55317f3f75
commit e2b329b2bb
20 changed files with 1534 additions and 0 deletions

View file

@ -0,0 +1,7 @@
import os
RENDERER_URL = os.environ.get("RENDERER_URL", "http://localhost:8002")
EXTRACTOR_URL = os.environ.get("EXTRACTOR_URL", "http://localhost:8003")
SEARCHER_URL = os.environ.get("SEARCHER_URL", "http://localhost:8001")
STAGE_TIMEOUT_S = float(os.environ.get("STAGE_TIMEOUT_S", "60"))

View file

@ -0,0 +1,22 @@
import json
import logging
import sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
return json.dumps(
{
"ts": self.formatTime(record),
"level": record.levelname.lower(),
"service": "orchestrator",
"msg": record.getMessage(),
}
)
def setup() -> logging.Logger:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler])
return logging.getLogger("orchestrator")

View file

@ -0,0 +1,54 @@
"""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 .logging_setup import setup
log = setup()
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.client = httpx.AsyncClient()
yield
await app.state.client.aclose()
app = FastAPI(title="LWSS Orchestrator", lifespan=lifespan)
class ScrapeRequest(BaseModel):
url: str
@app.get("/health")
async def health() -> dict:
"""Aggregate health across all downstream services."""
client: httpx.AsyncClient = app.state.client
services = {}
for name, base in [("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", "services": services}
@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)
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

View 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(),
}