/** * 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. */ /** * @module bxc/cluster/worker * * A cluster worker: one `MassiveCrawler` in daemon mode fed by the shards this * process owns in a {@link ShardedFrontier}. Links on owned shards are * enqueued locally; links on other shards are routed to their stream. * * @example * ```ts * const worker = await startClusterWorker({ frontier: "web", shards: 16, sqlitePath: "./index.sqlite" }); * process.on("SIGTERM", () => void worker.stop()); * await worker.done; * ``` */ import { type CrawlTier, MassiveCrawler, type MassiveCrawlerOptions, type MassiveCrawlerStats, } from "../crawler/MassiveCrawler.ts"; import { registrableDomain } from "../profiles/etld.ts"; import { stripQueryFamilyKey } from "../queue/frontier/scoring.ts"; import { RequestQueue } from "../queue/RequestQueue.ts"; import { ShardedFrontier, type ShardedFrontierJoinOptions, type ShardedFrontierStats, } from "../queue/sharded/RedisFrontier.ts"; export interface ClusterWorkerOptions { /** Redis URL. Default: `BXC_REDIS_URL`, `REDIS_URL`, `redis://127.0.0.1:6379`. */ redisUrl?: string; /** Frontier name shared by the workers of one crawl. */ frontier: string; /** Shard count (fixed at frontier creation). Default: stored value, else 16. */ shards?: number; /** Hard cap on owned shards. Default: fair share of the live workers. */ maxShards?: number; /** Unique worker id. Default: `-`. */ workerId?: string; /** Local frontier file; reuse it with the same `workerId` to resume after a crash. Default: `:memory:`. */ queuePath?: string; /** Index database. Default: `BXC_DB_PATH` or `~/.bxc/bxc.sqlite`. */ sqlitePath?: string; /** Tier ladder. Default: crawler default (`http → render → stealth`). */ ladder?: CrawlTier[]; /** Maximum concurrent requests. Default: 32. */ concurrency?: number; /** Crawl goal (anchor-text relevance). */ goal?: string; /** URLs submitted to the cluster at start. */ seeds?: string[]; /** Minimum delay between two requests to one registrable domain. Default: 0 (learned). */ perHostDelayMs?: number; /** Concurrent requests per registrable domain. Default: 8. */ maxInFlightPerHost?: number; /** Extra crawler options (depth, scope, proxies, fetcher, domain memory…). */ crawler?: Partial; /** Extra frontier options (lease timing, shard key function…). */ frontierOptions?: Partial; log?: (msg: string) => void; } export interface ClusterWorkerStats { crawler: MassiveCrawlerStats; frontier: ShardedFrontierStats; } export interface ClusterWorker { readonly frontier: ShardedFrontier; readonly crawler: MassiveCrawler; /** Shard-local frontier. */ readonly queue: RequestQueue; /** Resolves when the crawl loop has exited. */ readonly done: Promise; /** Graceful stop: crawler drained, routed links flushed, leases released. */ stop(): Promise; stats(): Promise; } function domainKey(url: string): string { try { return registrableDomain(url); } catch { return ""; } } /** Join a frontier and start crawling the owned shards. */ export async function startClusterWorker(options: ClusterWorkerOptions): Promise { const log = options.log ?? ((msg: string) => console.error(`[bxc-worker] ${msg}`)); const queue = RequestQueue.open(options.queuePath ?? ":memory:", { hostKeyFn: domainKey, perHostDelayMs: options.perHostDelayMs ?? 0, maxInFlightPerHost: options.maxInFlightPerHost ?? 8, familyKeyFn: stripQueryFamilyKey, goal: options.goal, enableRevisits: options.crawler?.enableRevisits ?? false, }); let frontier: ShardedFrontier; try { frontier = await ShardedFrontier.join({ redisUrl: options.redisUrl, name: options.frontier, shards: options.shards, maxShards: options.maxShards, workerId: options.workerId, log, ...options.frontierOptions, queue, }); } catch (err) { queue.close(); throw err; } const concurrency = Math.max(1, options.concurrency ?? 32); const crawler = new MassiveCrawler({ daemon: true, sqliteDbPath: options.sqlitePath, ladder: options.ladder, goal: options.goal, minConcurrency: Math.min(concurrency, 10), maxConcurrency: concurrency, // Seeds arrive through the cluster; sitemap discovery is per-process. ingestSitemaps: false, log, ...options.crawler, requestQueue: queue, routeLink: (url, opts) => frontier.route(url, opts), }); const done = crawler.run().catch((err) => { log(`crawler stopped with an error: ${err instanceof Error ? (err.stack ?? err.message) : err}`); }); if (options.seeds && options.seeds.length > 0) { const result = await frontier.submit(options.seeds); log(`submitted ${result.queued} seed(s) (${result.duplicates} already seen)`); } let stopping: Promise | null = null; return { frontier, crawler, queue, done, stop() { stopping ??= (async () => { crawler.stop(); await done; await frontier.leave(); queue.close(); crawler.db.close(); })(); return stopping; }, async stats() { return { crawler: crawler.stats(), frontier: await frontier.stats() }; }, }; }