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
69
services/renderer/src/browser.js
Normal file
69
services/renderer/src/browser.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { chromium } from "playwright";
|
||||
import { log } from "./log.js";
|
||||
|
||||
const WAIT_STATES = { networkidle: "networkidle", load: "load", domcontentloaded: "domcontentloaded" };
|
||||
|
||||
// Single shared browser, N pooled contexts enforced by a semaphore + FIFO queue.
|
||||
export function createBrowserPool({ concurrency, timeoutMs, waitPolicy }) {
|
||||
let browser = null;
|
||||
let active = 0;
|
||||
const waiting = [];
|
||||
|
||||
async function getBrowser() {
|
||||
if (!browser || !browser.isConnected()) {
|
||||
browser = await chromium.launch({ args: ["--disable-dev-shm-usage"] });
|
||||
log("info", "browser launched", {});
|
||||
}
|
||||
return browser;
|
||||
}
|
||||
|
||||
function acquire() {
|
||||
if (active < concurrency) {
|
||||
active++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise((resolve) => waiting.push(resolve));
|
||||
}
|
||||
|
||||
function release() {
|
||||
const next = waiting.shift();
|
||||
if (next) next();
|
||||
else active--;
|
||||
}
|
||||
|
||||
async function render(url, opts = {}) {
|
||||
const policy = opts.waitPolicy ?? waitPolicy;
|
||||
const timeout = opts.timeoutMs ?? timeoutMs;
|
||||
await acquire();
|
||||
let context;
|
||||
try {
|
||||
const b = await getBrowser();
|
||||
context = await b.newContext({ javaScriptEnabled: true });
|
||||
const page = await context.newPage();
|
||||
const waitUntil = WAIT_STATES[policy] ?? "networkidle";
|
||||
const response = await page.goto(url, { waitUntil, timeout });
|
||||
// networkidle can be flaky on chatty pages; goto already resolved, so a
|
||||
// short settle delay is enough when a fixed-delay policy is requested.
|
||||
if (policy === "delay") await page.waitForTimeout(Math.min(timeout, 3000));
|
||||
const html = await page.content();
|
||||
return {
|
||||
html,
|
||||
status: response?.status() ?? null,
|
||||
final_url: page.url(),
|
||||
rendered_at: new Date().toISOString(),
|
||||
};
|
||||
} finally {
|
||||
if (context) await context.close().catch(() => {});
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
render,
|
||||
isReady: () => browser?.isConnected() ?? false,
|
||||
stats: () => ({ active, waiting: waiting.length, concurrency }),
|
||||
close: async () => {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
}
|
||||
42
services/renderer/src/cache.js
Normal file
42
services/renderer/src/cache.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import Redis from "ioredis";
|
||||
import { log } from "./log.js";
|
||||
|
||||
// Redis-backed cache that degrades to a no-op when Redis is absent/unreachable,
|
||||
// so the renderer never hard-fails on the cache layer.
|
||||
export function createCache(redisUrl) {
|
||||
if (!redisUrl) {
|
||||
log("warn", "no REDIS_URL configured; render cache disabled", {});
|
||||
return { get: async () => null, set: async () => {}, isReady: async () => false };
|
||||
}
|
||||
|
||||
const redis = new Redis(redisUrl, {
|
||||
maxRetriesPerRequest: 1,
|
||||
retryStrategy: (times) => Math.min(times * 500, 5000),
|
||||
lazyConnect: false,
|
||||
});
|
||||
redis.on("error", (err) => log("warn", "redis error", { error: String(err.message) }));
|
||||
|
||||
return {
|
||||
async get(key) {
|
||||
try {
|
||||
return await redis.get(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
async set(key, value, ttl) {
|
||||
try {
|
||||
await redis.set(key, value, "EX", ttl);
|
||||
} catch {
|
||||
/* cache write failures are non-fatal */
|
||||
}
|
||||
},
|
||||
async isReady() {
|
||||
try {
|
||||
return (await redis.ping()) === "PONG";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
5
services/renderer/src/log.js
Normal file
5
services/renderer/src/log.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export function log(level, msg, fields) {
|
||||
process.stdout.write(
|
||||
JSON.stringify({ ts: new Date().toISOString(), level, service: "renderer", msg, ...fields }) + "\n"
|
||||
);
|
||||
}
|
||||
68
services/renderer/src/server.js
Normal file
68
services/renderer/src/server.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import express from "express";
|
||||
import { createBrowserPool } from "./browser.js";
|
||||
import { createCache } from "./cache.js";
|
||||
import { log } from "./log.js";
|
||||
|
||||
const PORT = parseInt(process.env.PORT ?? "8002", 10);
|
||||
const REDIS_URL = process.env.REDIS_URL ?? "";
|
||||
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 cache = createCache(REDIS_URL);
|
||||
const pool = createBrowserPool({
|
||||
concurrency: CONCURRENCY,
|
||||
timeoutMs: TIMEOUT_MS,
|
||||
waitPolicy: WAIT_POLICY,
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "1mb" }));
|
||||
|
||||
app.get("/health", async (req, res) => {
|
||||
res.json({
|
||||
status: "ok",
|
||||
service: "renderer",
|
||||
browser: pool.isReady(),
|
||||
redis: await cache.isReady(),
|
||||
queue: pool.stats(),
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/render", async (req, res) => {
|
||||
const { url, wait_policy, timeout_ms, bypass_cache } = req.body ?? {};
|
||||
if (!url || typeof url !== "string" || !/^https?:\/\//i.test(url)) {
|
||||
return res.status(400).json({ error: "body must include an http(s) 'url'" });
|
||||
}
|
||||
|
||||
const cacheKey = `render:${url}`;
|
||||
if (!bypass_cache) {
|
||||
const hit = await cache.get(cacheKey);
|
||||
if (hit) {
|
||||
log("info", "render cache hit", { url });
|
||||
return res.json({ ...JSON.parse(hit), cache: "hit" });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await pool.render(url, {
|
||||
waitPolicy: wait_policy,
|
||||
timeoutMs: timeout_ms,
|
||||
});
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(PORT, () => log("info", "renderer listening", { port: PORT }));
|
||||
|
||||
for (const sig of ["SIGINT", "SIGTERM"]) {
|
||||
process.on(sig, async () => {
|
||||
await pool.close();
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue