M5: hardening — retries, per-domain rate limiting, resource limits, docs
- renderer: per-domain politeness limiter (Redis fixed window, in-memory fallback; over-limit requests wait bounded, 429 past deadline); render retry with DNS-failure fast-fail - orchestrator: one retry on connection-level stage failures (not timeouts) - compose: per-container CPU/memory limits; all hardening knobs env-driven and documented in .env.example - README: quick start, MCP + REST usage, architecture, config, dev workflow Verified: rate limit window enforced (3rd request waited for reset), full scrape + MCP web_search smoke green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
a70a6b5f5f
commit
64ffeabd49
7 changed files with 212 additions and 10 deletions
12
.env.example
12
.env.example
|
|
@ -12,3 +12,15 @@ EXTRACT_CACHE_TTL=3600
|
|||
RENDER_CONCURRENCY=4
|
||||
RENDER_TIMEOUT_MS=30000
|
||||
RENDER_WAIT_POLICY=networkidle
|
||||
RENDER_RETRIES=1
|
||||
|
||||
# Politeness: max renders per domain per window
|
||||
DOMAIN_RATE_LIMIT=10
|
||||
DOMAIN_RATE_WINDOW_S=10
|
||||
|
||||
# Timeouts
|
||||
STAGE_TIMEOUT_S=60
|
||||
SEARCH_TIMEOUT_S=15
|
||||
|
||||
# SearXNG
|
||||
SEARXNG_SECRET=change-me-lwss-internal
|
||||
|
|
|
|||
80
README.md
Normal file
80
README.md
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
# Local Web Search Stack (LWSS)
|
||||
|
||||
Self-hosted, private web search + page retrieval for local LLMs — a functional
|
||||
replacement for Tavily/Serper/Firecrawl, exposed as an **MCP server**. No SaaS
|
||||
in the request path, no per-call fees, no LLM anywhere in the stack (the calling
|
||||
model does its own ranking/filtering; extraction is purely mechanical).
|
||||
|
||||
See [PRD.md](PRD.md) for full requirements and architecture.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp .env.example .env # optional; defaults work
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
The orchestrator is the only exposed service, on port 8000.
|
||||
|
||||
### MCP (primary interface)
|
||||
|
||||
Streamable HTTP endpoint: `http://localhost:8000/mcp`
|
||||
|
||||
Claude Code:
|
||||
|
||||
```bash
|
||||
claude mcp add --transport http local-web-search http://localhost:8000/mcp
|
||||
```
|
||||
|
||||
Tools:
|
||||
|
||||
| Tool | Args | Returns |
|
||||
|---|---|---|
|
||||
| `web_search` | `query`, `max_results=5`, `include_content=true` | ranked results: url, title, snippet (+ cleaned page text) |
|
||||
| `fetch_url` | `url` | cleaned text, title, metadata for one page |
|
||||
|
||||
### REST (debug / non-MCP clients)
|
||||
|
||||
```bash
|
||||
curl -X POST localhost:8000/search -d '{"query":"..."}' -H 'content-type: application/json'
|
||||
curl -X POST localhost:8000/search/contents -d '{"query":"...","max_results":5}' -H 'content-type: application/json'
|
||||
curl -X POST localhost:8000/scrape -d '{"url":"https://..."}' -H 'content-type: application/json'
|
||||
curl localhost:8000/health
|
||||
```
|
||||
|
||||
Every REST response includes a `trace`: per-stage timings, cache hit/miss, and
|
||||
a `degraded` list naming stages that fell back or partially failed.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
MCP client → orchestrator (REST+MCP) → searcher → searxng (local)
|
||||
→ renderer (Playwright)
|
||||
→ extractor (Trafilatura + readability)
|
||||
redis: search / rendered-HTML / extracted-text caches
|
||||
```
|
||||
|
||||
- **searcher** — queries the SearXNG pool (file-based list in
|
||||
`config/instances.yml`, failover mode; add instances there for rotation
|
||||
later), normalizes + dedups results.
|
||||
- **renderer** — always renders via headless Chromium; single browser, pooled
|
||||
contexts, concurrency cap + queue; per-domain rate limiting (Redis token
|
||||
window); render retry with DNS-failure fast-fail; Redis HTML cache.
|
||||
- **extractor** — mechanical extraction only: Trafilatura (precision → recall)
|
||||
then readability-lxml fallback; flags thin content.
|
||||
- **orchestrator** — sequencing, per-URL parallelism, partial-result
|
||||
degradation, scrape-result cache, aggregated `/health`.
|
||||
|
||||
## Configuration
|
||||
|
||||
All knobs are env vars (see `.env.example`): cache TTLs, renderer concurrency
|
||||
and timeouts, per-domain rate limit, stage timeouts, SearXNG secret. The
|
||||
SearXNG instance pool lives in `config/instances.yml` (hand-editable; reloaded
|
||||
on change without restart).
|
||||
|
||||
## Development
|
||||
|
||||
Python services run directly with uvicorn (`--app-dir services/<name>`), the
|
||||
renderer with `node services/renderer/src/server.js`. Everything degrades
|
||||
gracefully without Redis (caching disabled). Each service is curl-able in
|
||||
isolation on its own port: searcher 8001, renderer 8002, extractor 8003.
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
services:
|
||||
orchestrator:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1"
|
||||
memory: 512M
|
||||
build: services/orchestrator
|
||||
ports:
|
||||
- "${ORCHESTRATOR_PORT:-8000}:8000"
|
||||
|
|
@ -9,6 +14,7 @@ services:
|
|||
SEARCHER_URL: http://searcher:8001
|
||||
REDIS_URL: redis://redis:6379
|
||||
EXTRACT_CACHE_TTL: ${EXTRACT_CACHE_TTL:-3600}
|
||||
STAGE_TIMEOUT_S: ${STAGE_TIMEOUT_S:-60}
|
||||
depends_on:
|
||||
- searcher
|
||||
- renderer
|
||||
|
|
@ -21,10 +27,16 @@ services:
|
|||
retries: 3
|
||||
|
||||
searcher:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 256M
|
||||
build: services/searcher
|
||||
environment:
|
||||
REDIS_URL: redis://redis:6379
|
||||
SEARCH_CACHE_TTL: ${SEARCH_CACHE_TTL:-300}
|
||||
SEARCH_TIMEOUT_S: ${SEARCH_TIMEOUT_S:-15}
|
||||
INSTANCES_FILE: /config/instances.yml
|
||||
volumes:
|
||||
- ./config:/config:ro
|
||||
|
|
@ -38,6 +50,11 @@ services:
|
|||
retries: 3
|
||||
|
||||
searxng:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1"
|
||||
memory: 512M
|
||||
image: searxng/searxng:latest
|
||||
environment:
|
||||
SEARXNG_SECRET: ${SEARXNG_SECRET:-change-me-lwss-internal}
|
||||
|
|
@ -46,6 +63,11 @@ services:
|
|||
- ./searxng:/etc/searxng:ro
|
||||
|
||||
renderer:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2"
|
||||
memory: 2G
|
||||
build: services/renderer
|
||||
environment:
|
||||
REDIS_URL: redis://redis:6379
|
||||
|
|
@ -53,6 +75,9 @@ services:
|
|||
RENDER_CONCURRENCY: ${RENDER_CONCURRENCY:-4}
|
||||
RENDER_TIMEOUT_MS: ${RENDER_TIMEOUT_MS:-30000}
|
||||
RENDER_WAIT_POLICY: ${RENDER_WAIT_POLICY:-networkidle}
|
||||
RENDER_RETRIES: ${RENDER_RETRIES:-1}
|
||||
DOMAIN_RATE_LIMIT: ${DOMAIN_RATE_LIMIT:-10}
|
||||
DOMAIN_RATE_WINDOW_S: ${DOMAIN_RATE_WINDOW_S:-10}
|
||||
depends_on:
|
||||
- redis
|
||||
init: true
|
||||
|
|
@ -63,6 +88,11 @@ services:
|
|||
retries: 3
|
||||
|
||||
extractor:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1"
|
||||
memory: 512M
|
||||
build: services/extractor
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8003/health')"]
|
||||
|
|
@ -71,6 +101,11 @@ services:
|
|||
retries: 3
|
||||
|
||||
redis:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 640M
|
||||
image: redis:7-alpine
|
||||
command: redis-server --maxmemory 512mb --maxmemory-policy allkeys-lru
|
||||
healthcheck:
|
||||
|
|
|
|||
|
|
@ -38,8 +38,16 @@ class StageError(Exception):
|
|||
|
||||
|
||||
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:
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { log } from "./log.js";
|
|||
export function createCache(redisUrl) {
|
||||
if (!redisUrl) {
|
||||
log("warn", "no REDIS_URL configured; render cache disabled", {});
|
||||
return { get: async () => null, set: async () => {}, isReady: async () => false };
|
||||
return { get: async () => null, set: async () => {}, isReady: async () => false, redis: null };
|
||||
}
|
||||
|
||||
const redis = new Redis(redisUrl, {
|
||||
|
|
@ -17,6 +17,7 @@ export function createCache(redisUrl) {
|
|||
redis.on("error", (err) => log("warn", "redis error", { error: String(err.message) }));
|
||||
|
||||
return {
|
||||
redis,
|
||||
async get(key) {
|
||||
try {
|
||||
return await redis.get(key);
|
||||
|
|
|
|||
44
services/renderer/src/ratelimit.js
Normal file
44
services/renderer/src/ratelimit.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { log } from "./log.js";
|
||||
|
||||
// Per-domain politeness limiter: fixed window of `limit` renders per `windowS`
|
||||
// seconds per domain. Backed by Redis (shared across replicas) with an
|
||||
// in-memory fallback. Over-limit requests wait (bounded) instead of failing,
|
||||
// since callers are internal pipeline stages.
|
||||
export function createRateLimiter(cache, { limit, windowS, maxWaitMs, redis }) {
|
||||
const local = new Map(); // domain -> {count, resetAt}
|
||||
|
||||
async function tryAcquire(domain) {
|
||||
if (redis) {
|
||||
try {
|
||||
const key = `ratelimit:${domain}`;
|
||||
const count = await redis.incr(key);
|
||||
if (count === 1) await redis.expire(key, windowS);
|
||||
return count <= limit;
|
||||
} catch {
|
||||
/* fall through to local */
|
||||
}
|
||||
}
|
||||
const now = Date.now();
|
||||
const entry = local.get(domain);
|
||||
if (!entry || now >= entry.resetAt) {
|
||||
local.set(domain, { count: 1, resetAt: now + windowS * 1000 });
|
||||
return true;
|
||||
}
|
||||
entry.count++;
|
||||
return entry.count <= limit;
|
||||
}
|
||||
|
||||
return {
|
||||
async acquire(url) {
|
||||
const domain = new URL(url).hostname;
|
||||
const deadline = Date.now() + maxWaitMs;
|
||||
while (!(await tryAcquire(domain))) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error(`per-domain rate limit exceeded for ${domain}`);
|
||||
}
|
||||
log("info", "rate limited, waiting", { domain });
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import express from "express";
|
||||
import { createBrowserPool } from "./browser.js";
|
||||
import { createCache } from "./cache.js";
|
||||
import { createRateLimiter } from "./ratelimit.js";
|
||||
import { log } from "./log.js";
|
||||
|
||||
const PORT = parseInt(process.env.PORT ?? "8002", 10);
|
||||
|
|
@ -9,8 +10,17 @@ const CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL ?? "3600", 10);
|
|||
const CONCURRENCY = parseInt(process.env.RENDER_CONCURRENCY ?? "4", 10);
|
||||
const TIMEOUT_MS = parseInt(process.env.RENDER_TIMEOUT_MS ?? "30000", 10);
|
||||
const WAIT_POLICY = process.env.RENDER_WAIT_POLICY ?? "networkidle";
|
||||
const RETRIES = parseInt(process.env.RENDER_RETRIES ?? "1", 10);
|
||||
const DOMAIN_RATE_LIMIT = parseInt(process.env.DOMAIN_RATE_LIMIT ?? "10", 10);
|
||||
const DOMAIN_RATE_WINDOW_S = parseInt(process.env.DOMAIN_RATE_WINDOW_S ?? "10", 10);
|
||||
|
||||
const cache = createCache(REDIS_URL);
|
||||
const limiter = createRateLimiter(cache, {
|
||||
limit: DOMAIN_RATE_LIMIT,
|
||||
windowS: DOMAIN_RATE_WINDOW_S,
|
||||
maxWaitMs: 30000,
|
||||
redis: cache.redis,
|
||||
});
|
||||
const pool = createBrowserPool({
|
||||
concurrency: CONCURRENCY,
|
||||
timeoutMs: TIMEOUT_MS,
|
||||
|
|
@ -46,15 +56,27 @@ app.post("/render", async (req, res) => {
|
|||
}
|
||||
|
||||
try {
|
||||
const result = await pool.render(url, {
|
||||
waitPolicy: wait_policy,
|
||||
timeoutMs: timeout_ms,
|
||||
});
|
||||
await limiter.acquire(url);
|
||||
let result;
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt <= RETRIES; attempt++) {
|
||||
try {
|
||||
result = await pool.render(url, { waitPolicy: wait_policy, timeoutMs: timeout_ms });
|
||||
break;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
// DNS failures won't resolve themselves between attempts; bail early.
|
||||
if (String(err).includes("ERR_NAME_NOT_RESOLVED")) break;
|
||||
if (attempt < RETRIES) log("warn", "render retry", { url, attempt: attempt + 1 });
|
||||
}
|
||||
}
|
||||
if (!result) throw lastErr;
|
||||
await cache.set(cacheKey, JSON.stringify(result), CACHE_TTL);
|
||||
res.json({ ...result, cache: "miss" });
|
||||
} catch (err) {
|
||||
log("error", "render failed", { url, error: String(err) });
|
||||
res.status(502).json({ error: `render failed: ${err.message}`, url });
|
||||
const status = String(err.message).includes("rate limit") ? 429 : 502;
|
||||
res.status(status).json({ error: `render failed: ${err.message}`, url });
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue