/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * `bxc worker` — join a sharded crawl cluster (Redis streams + leases) and * crawl the owned shards; `bxc worker seed` submits URLs; `bxc worker stats` * prints the cluster view. See docs/CLUSTER.md. */ import { intFlag, parseFlags, parseLadder } from "../cluster/cli-args.ts"; import type { CommonOptions } from "./shared.ts"; const USAGE = `bxc worker --redis --frontier [options] bxc worker seed --redis --frontier [--force] bxc worker stats --redis --frontier [--json] Worker options: --redis Redis URL (default BXC_REDIS_URL, REDIS_URL, redis://127.0.0.1:6379) --frontier Frontier name shared by the cluster --shards Shard count when creating the frontier (default 16) --max-shards Cap on shards owned by this worker (default: fair share) --worker-id Unique, stable worker id (default -) --queue Local frontier file for crash resume (default :memory:) --sqlite Index database (default BXC_DB_PATH or ~/.bxc/bxc.sqlite) --ladder Fetch tiers, e.g. http,render,stealth --concurrency Concurrent requests (default 32) --max-depth Link depth limit (default 10) --goal Crawl goal for focused crawling --lease-ms Shard lease TTL (default 15000) --seed Submit seeds when starting -h, --help Show this message `; export async function main(argv: string[] = process.argv.slice(2), opts?: CommonOptions): Promise { if (argv.includes("-h") || argv.includes("--help")) { Bun.stdout.write(USAGE); return; } let flags: ReturnType; try { flags = parseFlags(argv, { booleans: ["force"], lists: ["seed"] }); } catch (err) { console.error(`[bxc-worker] ${(err as Error).message}\n`); Bun.stderr.write(USAGE); process.exit(2); } const [command, ...rest] = flags.positionals; const frontier = flags.values.get("frontier"); if (!frontier) { console.error("[bxc-worker] --frontier is required\n"); Bun.stderr.write(USAGE); process.exit(2); } const redisUrl = flags.values.get("redis"); const quiet = opts?.quiet === true; const log = (msg: string) => { if (!quiet) console.error(`[bxc-worker] ${msg}`); }; if (command === "seed" || command === "stats") { const { ShardedFrontier } = await import("../queue/sharded/RedisFrontier.ts"); const client = await ShardedFrontier.connect({ redisUrl, name: frontier, shards: intFlag(flags, "shards") }); try { if (command === "seed") { const { normalizeUrl } = await import("../rust/bridge.ts"); const urls = [...rest, ...(flags.lists.get("seed") ?? [])].map((u) => normalizeUrl(u)); if (urls.length === 0) throw new Error("no URL to submit"); const result = await client.submit(urls, { force: flags.booleans.has("force") }); Bun.stdout.write( opts?.json ? `${JSON.stringify(result)}\n` : `queued ${result.queued}, already seen ${result.duplicates} (frontier ${frontier}, ${client.shards} shards)\n`, ); } else { const stats = await client.stats(); if (opts?.json) { Bun.stdout.write(`${JSON.stringify(stats, null, 2)}\n`); } else { Bun.stdout.write( `frontier ${stats.name}: ${stats.shards} shards, ${stats.workers.length} live worker(s) [${stats.workers.join(", ")}]\n` + `seen-set: ~${stats.seen.count} URLs, est. FPR ${(stats.seen.estimatedFalsePositiveRate * 100).toFixed(3)} %\n` + stats.perShard .map((s) => ` shard ${String(s.shard).padStart(3)} backlog ${String(s.length).padStart(8)} pending ${String(s.pending).padStart(6)} owner ${s.owner ?? "-"}`) .join("\n") + "\n", ); } } } finally { await client.leave(); } return; } if (command !== undefined) { console.error(`[bxc-worker] unknown command: ${command}\n`); Bun.stderr.write(USAGE); process.exit(2); } const { startClusterWorker } = await import("../cluster/worker.ts"); const maxDepth = intFlag(flags, "max-depth"); const leaseMs = intFlag(flags, "lease-ms"); const worker = await startClusterWorker({ redisUrl, frontier, shards: intFlag(flags, "shards"), maxShards: intFlag(flags, "max-shards"), workerId: flags.values.get("worker-id"), queuePath: flags.values.get("queue"), sqlitePath: flags.values.get("sqlite"), ladder: parseLadder(flags.values.get("ladder")), concurrency: intFlag(flags, "concurrency"), goal: flags.values.get("goal"), seeds: flags.lists.get("seed"), crawler: { ...(maxDepth !== undefined ? { maxDepth } : {}), ...(opts?.proxy ? { proxyPool: [opts.proxy] } : {}), }, frontierOptions: leaseMs !== undefined ? { leaseMs } : {}, log, }); log(`worker ${worker.frontier.workerId} joined frontier ${frontier} (${worker.frontier.shards} shards)`); const report = setInterval(() => { const crawl = worker.crawler.stats(); log( `shards [${worker.frontier.ownedShards().join(",")}] fetched ${crawl.fetched} indexed ${crawl.indexed} pending ${crawl.queue.pending} forwarded ${worker.frontier.counters().forwarded}`, ); }, 60_000); report.unref?.(); let signals = 0; const shutdown = (signal: string) => { signals++; if (signals > 1) process.exit(130); log(`${signal}: draining in-flight requests and releasing shards (again to force)`); clearInterval(report); worker.stop().then( () => process.exit(0), (err) => { console.error(`[bxc-worker] shutdown failed: ${err}`); process.exit(1); }, ); }; process.on("SIGINT", () => shutdown("SIGINT")); process.on("SIGTERM", () => shutdown("SIGTERM")); await worker.done; }