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:
User 2026-07-05 22:11:28 -07:00
parent a70a6b5f5f
commit 64ffeabd49
7 changed files with 212 additions and 10 deletions

View file

@ -38,10 +38,18 @@ class StageError(Exception):
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
# 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}")

View file

@ -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);

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

View file

@ -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 });
}
});