/** * 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/crawler/MassiveCrawler * * Continuous web indexer producing an agent-ready, deduplicated, citable index. * * Per request: * 1. **Frontier v2** (`RequestQueue`): per-host scheduling with learned * politeness delays, OPIC + anchor-relevance + depth scoring, duplicate * families, change-rate revisits. * 2. **Access layer**: the tier ladder (default `http → render → stealth`, * unavailable tiers skipped) starts at the tier domain memory learned for * the registrable domain; proxies are chosen by Thompson sampling; every * attempt (success / blocked / throttled / error) is recorded. Pages come * from one `PagePool` per (tier, proxy), so browser tiers reuse processes * instead of spawning one per URL. * 3. **Document pipeline**: main-content extraction, Markdown, structural * chunks with offsets, canonical URL, content hash and SimHash. * 4. **Dedup**: canonical redirection, exact (content hash) and near * (SimHash ≤ 3 bits) duplicates are not re-indexed; content-neutral query * parameters are learned and stripped before enqueueing. * 5. **Index**: idempotent document + chunk upserts with provenance * (fetch time, tier, validators, hashes), optional chunk embeddings. */ import { AphrodyPg } from "../db/AphrodyPg.ts"; import { BxcDB, type ChunkInput, type DocumentInput } from "../db/BxcDB.ts"; import { type Embedder, defaultEmbedder } from "../embed/embedder.ts"; import type { PageOptions } from "../api/browser.ts"; import type { AnyPage } from "../api/types.ts"; import { PagePool } from "../pool/PagePool.ts"; import { detectEscalationSignal, type EscalationStep, outcomeForSignal, } from "../profiles/auto-escalation.ts"; import { DomainMemory, parseRetryAfter } from "../profiles/domain-memory.ts"; import { registrableDomain } from "../profiles/etld.ts"; import { RequestQueue, type MarkDoneOptions } from "../queue/RequestQueue.ts"; import { CuckooFilter } from "../queue/frontier/cuckoo-filter.ts"; import { stripQueryFamilyKey } from "../queue/frontier/scoring.ts"; import { ingestSeeds } from "../queue/frontier/seeds.ts"; import { normalizeUrl, simhashDistance } from "../rust/bridge.ts"; import { BasicCrawler, type BasicCrawlerOptions, type CrawlContext } from "./Crawler.ts"; import { type ProcessedDocument, processDocument } from "./document-pipeline.ts"; import { ParamLearner } from "./url-param-learner.ts"; /** Fetch tiers the massive crawler can use, cheapest first. */ export type CrawlTier = "http" | "render" | "fast" | "stealth" | "max"; const DEFAULT_LADDER: readonly CrawlTier[] = ["http", "render", "stealth"]; export interface FetchedPage { html: string; status: number; finalUrl: string; headers: Record; } /** Fetch one URL with a tier (injectable for tests). */ export type TierFetcher = (tier: CrawlTier, url: string, proxy: string | undefined) => Promise; export interface MassiveCrawlerOptions { requestQueueName?: string; allowedDomains?: string[]; excludePatterns?: string[]; maxDepth?: number; maxRequests?: number; minConcurrency?: number; maxConcurrency?: number; maxRetries?: number; daemon?: boolean; proxyPool?: string[]; sqliteDbPath?: string; postgresUrl?: string; /** Accepted for compatibility; politeness is learned per domain. */ obeyRobots?: boolean; /** Accepted for compatibility; see `perHostDelayMs`. */ maxRequestsPerHostPerSec?: number; /** Embed chunks with the default embedder. */ enableVectors?: boolean; batchFlushSize?: number; log?: (msg: string) => void; /** Tier ladder, cheapest first. Default: `http → render → stealth`. */ ladder?: CrawlTier[]; /** Domain memory instance, or `false` to disable learning. Default: shared. */ domainMemory?: DomainMemory | false; /** Minimum delay between two requests to one registrable domain. Default: 0. */ perHostDelayMs?: number; /** Maximum concurrent requests per registrable domain. Default: 8. */ maxInFlightPerHost?: number; /** Crawl goal for anchor-text relevance (focused crawling). */ goal?: string; /** Re-crawl pages according to their estimated change rate. */ enableRevisits?: boolean; /** Skip indexing canonical variants and near-duplicates. Default: true. */ dedup?: boolean; /** SimHash bit distance treated as near-duplicate. Default: 3. */ nearDuplicateBits?: number; /** Tasks per browser page before it is recycled. Default: 50. */ maxUsesPerBrowserPage?: number; /** * Concurrent pages per browser tier and proxy (each `stealth`/`max` page is * a Chrome process; `render` pages are V8 isolates). Default: 8. */ maxBrowserPages?: number; /** Chunk size for the index. Default: 1200 characters. */ maxChunkChars?: number; /** Custom fetcher (tests, alternative transports). */ fetcher?: TierFetcher; /** Embedder used when `enableVectors` is set. Default: `defaultEmbedder()`. */ embedder?: Embedder; /** * Discover sitemaps (robots.txt `Sitemap:` lines, `/sitemap.xml`) and feeds * of each seed origin and enqueue their URLs with recency priority. * Default: true. */ ingestSitemaps?: boolean; /** * Persisted seen-set file (Cuckoo filter) of every URL this crawler has * enqueued, across runs. Used to skip already-known sitemap/feed entries * and exposed through {@link MassiveCrawler.hasSeen} for routing. * Default: next to a file-backed frontier (`.seen`), in memory otherwise. */ seenSetPath?: string | false; /** * Frontier to use instead of opening `requestQueueName` (e.g. a shard-local * queue fed by a cluster). Politeness/goal options then belong to it. */ requestQueue?: RequestQueue; /** * Called with links whose registrable domain this process does not own * (sharded crawling). Returning `true` means the link was routed elsewhere * and must not be enqueued locally. */ routeLink?: (url: string, opts: { depth: number; anchorText: string; parent: string }) => boolean; } export interface MassiveCrawlItem { url: string; title: string; markdown: string; html: string; status: number; profile: string; structured: unknown; openapi: unknown; vector?: number[]; depth: number; } export interface MassiveCrawlerStats { queue: ReturnType; buffered: number; fetched: number; indexed: number; unchanged: number; canonicalRedirects: number; exactDuplicates: number; nearDuplicates: number; blocked: number; /** Queued URLs skipped because a learned parameter mapped them onto a known URL. */ learnedParamSkips: number; /** Attempts per tier. */ tierAttempts: Record; /** Pages created per tier (spawn cost driver for browser tiers). */ pagesCreated: Record; } type NavigablePage = AnyPage & { goto(url: string): Promise<{ status?: number; url?: string; headers?: Record } | null>; content(): Promise; }; export class MassiveCrawler { readonly #options: MassiveCrawlerOptions; readonly #requestQueue: RequestQueue; readonly #db: BxcDB; readonly #pg?: AphrodyPg; readonly #allowedDomains?: string[]; readonly #exclude: RegExp[]; readonly #maxDepth: number; readonly #proxyPool: string[]; readonly #enableVectors: boolean; readonly #log: (msg: string) => void; readonly #memory: DomainMemory | null; readonly #learner = new ParamLearner(); readonly #pools = new Map(); readonly #dedup: boolean; readonly #nearBits: number; readonly #batchFlushSize: number; #ladder: CrawlTier[] | null = null; #crawler?: BasicCrawler; #isRunning = false; #recoveryTimer?: ReturnType; #embedder: Embedder | null = null; #lastIndexSave = Date.now(); #seen: CuckooFilter = new CuckooFilter({ initialCapacity: 1_000_000 }); readonly #seenPath: string | null; /** Documents waiting for a batched upsert. */ #buffer: DocumentInput[] = []; /** SimHashes of buffered (not yet flushed) documents, for near-dup checks. */ readonly #bufferedSimhashes = new Map(); readonly #counters = { fetched: 0, indexed: 0, unchanged: 0, canonicalRedirects: 0, exactDuplicates: 0, nearDuplicates: 0, blocked: 0, learnedParamSkips: 0, tierAttempts: {} as Record, pagesCreated: {} as Record, }; constructor(opts: MassiveCrawlerOptions = {}) { this.#options = opts; this.#requestQueue = opts.requestQueue ?? RequestQueue.open(opts.requestQueueName ?? "bxc-massive-frontier", { maxRetries: opts.maxRetries ?? 3, hostKeyFn: (url) => { try { return registrableDomain(url); } catch { return ""; } }, perHostDelayMs: opts.perHostDelayMs ?? 0, maxInFlightPerHost: opts.maxInFlightPerHost ?? 8, familyKeyFn: stripQueryFamilyKey, goal: opts.goal, enableRevisits: opts.enableRevisits ?? false, }); this.#db = new BxcDB(opts.sqliteDbPath); if (opts.postgresUrl || process.env.APHRODY_PG_URL) { this.#pg = new AphrodyPg(opts.postgresUrl); } this.#memory = opts.domainMemory === false ? null : (opts.domainMemory ?? DomainMemory.shared()); this.#allowedDomains = opts.allowedDomains; this.#exclude = (opts.excludePatterns ?? []).map((m) => new RegExp(m)); this.#maxDepth = opts.maxDepth ?? 10; this.#proxyPool = opts.proxyPool ?? []; this.#enableVectors = opts.enableVectors ?? false; this.#dedup = opts.dedup ?? true; this.#nearBits = opts.nearDuplicateBits ?? 3; this.#batchFlushSize = opts.batchFlushSize ?? 50; this.#log = opts.log ?? ((msg) => console.log(`[massive-crawler] ${msg}`)); const queueName = opts.requestQueueName ?? ""; this.#seenPath = opts.seenSetPath === false ? null : (opts.seenSetPath ?? (!opts.requestQueue && (queueName.includes("/") || queueName.includes("\\")) ? `${queueName}.seen` : null)); } /** Tier ladder with unavailable tiers removed. */ async #resolveLadder(): Promise { if (this.#ladder) return this.#ladder; const wanted = this.#options.ladder ?? [...DEFAULT_LADDER]; const available: CrawlTier[] = []; for (const tier of wanted) { if (tier === "render" && !this.#options.fetcher) { try { // Resolved at runtime: the render cdylib bindings are optional. const renderModule = "../render/native-render.ts"; const render = (await import(renderModule)) as { isRenderAvailable?: () => boolean }; if (!render.isRenderAvailable?.()) continue; } catch { continue; } } available.push(tier); } this.#ladder = available.length > 0 ? available : ["http"]; return this.#ladder; } async run(seedUrls?: string[]): Promise { if (this.#isRunning) return; this.#isRunning = true; await this.#resolveLadder(); if (this.#enableVectors) { this.#embedder = this.#options.embedder ?? (await defaultEmbedder()); if (!this.#embedder.semantic) { this.#log(`Embedder ${this.#embedder.model} is not semantic; install a local model with \`bxc install --models\``); } try { await this.#db.openVectorIndex(this.#embedder.model, this.#embedder.dim); } catch (err) { this.#log(`Vector index unavailable, using exact scan: ${err}`); } } if (this.#seenPath) { try { this.#seen = await CuckooFilter.load(this.#seenPath, { initialCapacity: 1_000_000 }); } catch (err) { this.#log(`Seen-set at ${this.#seenPath} unreadable (${err}); starting empty`); } } if (seedUrls && seedUrls.length > 0) { const seeds = seedUrls.map((rawUrl) => normalizeUrl(rawUrl)); for (const seed of seeds) this.#seen.add(seed); this.#requestQueue.addRequests(seeds.map((url) => ({ url, opts: { depth: 0, userData: { depth: 0 } } }))); if (this.#options.ingestSitemaps ?? true) await this.#ingestSitemaps(seeds); } // Periodic maintenance: stale locks, buffered writes, WAL checkpoints, revisits. this.#recoveryTimer = setInterval(() => { try { const recovered = this.#requestQueue.recoverStaleLocks(); if (recovered > 0) this.#log(`Auto-recovered ${recovered} stale requests`); void this.#flushBuffer(); void this.#saveSeen(); if (this.#embedder && Date.now() - this.#lastIndexSave > 5 * 60_000) { this.#lastIndexSave = Date.now(); this.#db.saveVectorIndex(); } this.#requestQueue.checkpoint("PASSIVE"); this.#db.checkpoint("PASSIVE"); if (this.#options.enableRevisits) this.#requestQueue.requeueDueRevisits(); } catch (err) { this.#log(`Maintenance error: ${err}`); } }, 30_000); const runner = (req: any, ctx: CrawlContext) => this.#executeRequest(req, ctx); class MassiveWorkerCrawler extends BasicCrawler { async processRequest(request: any): Promise { const context: CrawlContext = { request, enqueueLinks: async () => {}, pushData: async (data) => { if (this.dataset) await this.dataset.pushData(data); }, log: (msg) => this.log(msg), }; return runner(request, context); } } const crawlerOptions: BasicCrawlerOptions = { requestQueue: this.#requestQueue, minConcurrency: this.#options.minConcurrency ?? 10, maxConcurrency: this.#options.maxConcurrency ?? 100, maxRequestsPerCrawl: this.#options.maxRequests ?? Number.POSITIVE_INFINITY, daemon: this.#options.daemon ?? true, requestHandler: async () => {}, log: this.#log, }; this.#crawler = new MassiveWorkerCrawler(crawlerOptions); try { await this.#crawler.run(); } finally { if (this.#recoveryTimer) clearInterval(this.#recoveryTimer); await this.#flushBuffer(); await this.#saveSeen(); this.#db.checkpoint("FULL"); await this.#closePools(); this.#isRunning = false; } } async #saveSeen(): Promise { if (!this.#seenPath) return; try { await this.#seen.save(this.#seenPath); } catch (err) { this.#log(`Seen-set save failed: ${err}`); } } /** Enqueue sitemap and feed URLs of every seed origin (best effort). */ async #ingestSitemaps(seeds: string[]): Promise { const origins = new Set(); for (const seed of seeds) { try { origins.add(new URL(seed).origin); } catch { // Invalid seed; already reported by the frontier. } } const fetchText = async (url: string): Promise => { const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(15_000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const bytes = new Uint8Array(await res.arrayBuffer()); const gzipped = bytes[0] === 0x1f && bytes[1] === 0x8b; return new TextDecoder().decode(gzipped ? Bun.gunzipSync(bytes) : bytes); }; for (const origin of origins) { try { const result = await ingestSeeds(this.#requestQueue, origin, { fetchText, sitemaps: [`${origin}/sitemap.xml`], filter: (url) => this.#inScope(url) && this.#seen.add(this.#canonicalKey(url)), userData: { depth: 1 }, }); if (result.enqueued > 0) this.#log(`Seeded ${result.enqueued} URLs from sitemaps/feeds of ${origin}`); } catch (err) { this.#log(`Sitemap ingestion failed for ${origin}: ${err}`); } } } // ------------------------------------------------------------------------- // Fetching // ------------------------------------------------------------------------- #poolFor(tier: CrawlTier, proxy: string | undefined): PagePool { const key = `${tier}|${proxy ?? ""}`; let pool = this.#pools.get(key); if (!pool) { const browserTier = tier !== "http"; const crawlConcurrency = this.#options.maxConcurrency ?? 100; const browserPages = Math.max(1, this.#options.maxBrowserPages ?? 8); pool = new PagePool({ profile: tier as PageOptions["profile"], concurrency: browserTier ? Math.min(crawlConcurrency, browserPages) : crawlConcurrency, maxPages: browserTier ? browserPages : 256, maxUsesPerPage: browserTier && tier !== "render" ? (this.#options.maxUsesPerBrowserPage ?? 50) : Number.POSITIVE_INFINITY, pageOptions: tier === "http" ? { httpOpts: { profile: "chrome131", proxy, timeoutMs: 15_000 } } : { headless: true, proxy }, }); this.#pools.set(key, pool); } return pool; } #curlAvailable: boolean | null = null; /** `http` tier without libcurl-impersonate: Bun fetch with browser headers. */ async #plainHttpFetch(url: string, proxy: string | undefined): Promise { const { browserHeaders } = await import("../internal/browser-headers.ts"); const res = await fetch(url, { redirect: "follow", proxy, headers: browserHeaders(), signal: AbortSignal.timeout(15_000), } as RequestInit); return { html: await res.text(), status: res.status, finalUrl: res.url || url, headers: Object.fromEntries(res.headers.entries()), }; } async #fetch(tier: CrawlTier, url: string, proxy: string | undefined): Promise { if (this.#options.fetcher) return this.#options.fetcher(tier, url, proxy); if (tier === "http") { if (this.#curlAvailable === null) { const { isLibAvailable } = await import("../ffi/curl-impersonate.ts"); this.#curlAvailable = isLibAvailable(); } if (!this.#curlAvailable) return this.#plainHttpFetch(url, proxy); } return this.#poolFor(tier, proxy).use(async (page) => { const navigable = page as unknown as NavigablePage; const response = await navigable.goto(url); const status = typeof (response as { status?: unknown } | null)?.status === "function" ? (response as unknown as { status(): number }).status() : ((response?.status as number | undefined) ?? 200); return { html: await navigable.content(), status, finalUrl: response?.url || url, headers: response?.headers ?? {}, }; }); } /** * Walk the tier ladder from the tier domain memory recommends, recording * every attempt. Throws when every tier failed (the frontier retries later). */ async #fetchWithLadder(url: string): Promise { const ladder = await this.#resolveLadder(); const start = this.#memory?.startTier(url, ladder as unknown as EscalationStep[]) ?? ladder[0]; let index = Math.max(0, ladder.indexOf(start as CrawlTier)); let lastError = "no tier attempted"; for (; index < ladder.length; index++) { const tier = ladder[index] as CrawlTier; const proxy = this.#proxyPool.length > 0 ? (this.#memory?.chooseProxy(url, this.#proxyPool) ?? this.#proxyPool[0]) : undefined; this.#counters.tierAttempts[tier] = (this.#counters.tierAttempts[tier] ?? 0) + 1; const step = tier as unknown as EscalationStep; const started = performance.now(); let page: FetchedPage; try { page = await this.#fetch(tier, url, proxy); } catch (err) { lastError = err instanceof Error ? err.message : String(err); this.#memory?.recordAttempt(url, { tier: step, proxy, outcome: "error", reason: "navigation_error" }); continue; } const signal = detectEscalationSignal(page.html, page.status, { url, headers: new Headers(page.headers) }); if (signal) { const outcome = outcomeForSignal(signal, page.status); const retryAfter = page.headers["retry-after"]; this.#memory?.recordAttempt(url, { tier: step, proxy, status: page.status, outcome, reason: signal.reason, retryAfterMs: retryAfter ? parseRetryAfter(retryAfter) : undefined, }); if (this.#memory) { this.#requestQueue.setHostDelay(url, this.#memory.politenessDelayMs(url)); } lastError = `${signal.reason} (HTTP ${page.status}) on ${tier}`; if (outcome === "throttled") break; // Retry later on the same tier, not escalate. continue; } this.#memory?.recordAttempt(url, { tier: step, proxy, status: page.status, outcome: "success", latencyMs: performance.now() - started, }); return { ...page, tier }; } this.#counters.blocked++; throw new Error(`All tiers failed for ${url}: ${lastError}`); } // ------------------------------------------------------------------------- // Pipeline // ------------------------------------------------------------------------- #inScope(url: string): boolean { if (this.#exclude.some((rx) => rx.test(url))) return false; if (!this.#allowedDomains || this.#allowedDomains.length === 0) return true; try { const host = new URL(url).hostname; return this.#allowedDomains.some((d) => host === d || host.endsWith(`.${d}`)); } catch { return false; } } #canonicalKey(url: string): string { return this.#learner.normalize(normalizeUrl(url)); } #nearDuplicateOf(doc: ProcessedDocument, url: string): string | null { if (!doc.simhash) return null; for (const [bufferedUrl, simhash] of this.#bufferedSimhashes) { if (bufferedUrl !== url && simhashDistance(simhash, doc.simhash) <= this.#nearBits) return bufferedUrl; } const [match] = this.#db.findNearDuplicates(doc.simhash, this.#nearBits, url); return match?.url ?? null; } async #executeRequest(req: any, ctx: CrawlContext): Promise { const url = this.#canonicalKey(req.url); const depth = (req.depth as number | undefined) ?? (req.userData?.depth as number) ?? 0; // A parameter learned as content-neutral after this request was queued // can map it onto a URL the frontier already holds: skip the fetch. if (this.#dedup && url !== req.url && url !== req.uniqueKey && this.#requestQueue.has(url)) { this.#counters.learnedParamSkips++; await ctx.pushData({ url: req.url, depth, skipped: "learned-parameter", duplicateOf: url }); return {}; } const fetched = await this.#fetchWithLadder(url); this.#counters.fetched++; const finalUrl = this.#canonicalKey(fetched.finalUrl || url); const doc = processDocument(fetched.html, finalUrl, { maxChunkChars: this.#options.maxChunkChars }); this.#learner.observe(finalUrl, doc.simhash); let skipReason: "canonical" | "exact-duplicate" | "near-duplicate" | null = null; let duplicateOf: string | null = null; if (this.#dedup) { const canonical = doc.canonicalUrl ? this.#canonicalKey(doc.canonicalUrl) : null; if (canonical && canonical !== finalUrl && this.#inScope(canonical)) { skipReason = "canonical"; duplicateOf = canonical; this.#counters.canonicalRedirects++; this.#seen.add(canonical); this.#requestQueue.addRequests([{ url: canonical, opts: { depth, userData: { depth }, boost: 1 } }], { parent: req.uniqueKey, }); } else { const exact = this.#db.findByContentHash(doc.contentHash); if (exact && exact.url !== finalUrl) { skipReason = "exact-duplicate"; duplicateOf = exact.url; this.#counters.exactDuplicates++; } else { const near = this.#nearDuplicateOf(doc, finalUrl); if (near) { skipReason = "near-duplicate"; duplicateOf = near; this.#counters.nearDuplicates++; } } } } if (!skipReason) { await this.#index(doc, fetched, finalUrl, depth); this.#enqueueLinks(doc, req.uniqueKey, depth); } await ctx.pushData({ url: finalUrl, title: doc.title, status: fetched.status, depth, profile: fetched.tier, textLength: doc.text.length, engine: doc.engine, ...(skipReason ? { skipped: skipReason, duplicateOf } : {}), }); return { contentHash: doc.contentHash }; } async #index(doc: ProcessedDocument, fetched: FetchedPage & { tier: CrawlTier }, url: string, depth: number) { let chunks: ChunkInput[] = doc.chunks; if (this.#embedder && chunks.length > 0) { try { const vectors = await this.#embedder.embed( chunks.map((c) => [c.headingPath?.join(" > "), c.text].filter(Boolean).join("\n")), "passage", ); chunks = chunks.map((chunk, i) => ({ ...chunk, embedding: vectors[i] })); } catch (err) { this.#log(`Embedding failed for ${url}: ${err}`); } } this.#buffer.push({ url, profile: fetched.tier, status: fetched.status, content: fetched.html, metadata: { title: doc.title, depth, byline: doc.byline, published: doc.published, lang: doc.lang, description: doc.description, siteName: doc.siteName, wordCount: doc.wordCount, engine: doc.engine, }, markdown: doc.markdown, provenance: { canonicalUrl: doc.canonicalUrl, contentHash: doc.contentHash, simhash: doc.simhash, etag: fetched.headers.etag ?? null, lastModified: fetched.headers["last-modified"] ?? null, fetchedAt: Date.now(), }, chunks, chunkEmbeddingModel: this.#embedder?.model, }); if (doc.simhash) this.#bufferedSimhashes.set(url, doc.simhash); if (this.#buffer.length >= this.#batchFlushSize) await this.#flushBuffer(); if (this.#pg) { this.#pg .ingestScrape({ url, title: doc.title, markdown: doc.markdown, corpus: "bxc_massive", metadata: { depth, profile: fetched.tier, status: fetched.status }, }) .catch(() => {}); } } #enqueueLinks(doc: ProcessedDocument, parentKey: string, depth: number): void { if (depth >= this.#maxDepth) return; const seen = new Set(); const items: Array<{ url: string; opts: { depth: number; anchorText: string; userData: { depth: number }; boost?: number } }> = []; for (const anchor of doc.anchors) { const url = this.#canonicalKey(anchor.url); if (seen.has(url) || !this.#inScope(url)) continue; seen.add(url); // Known children still go through the frontier so OPIC credits them // their share of this page's cash; the seen-set only records them. this.#seen.add(url); if (this.#options.routeLink?.(url, { depth: depth + 1, anchorText: anchor.text, parent: parentKey })) continue; items.push({ url, opts: { depth: depth + 1, anchorText: anchor.text, userData: { depth: depth + 1 }, ...(anchor.nofollow ? { boost: -0.25 } : {}), }, }); } if (items.length > 0) this.#requestQueue.addRequests(items, { parent: parentKey }); } async #flushBuffer(): Promise { if (this.#buffer.length === 0) return; const batch = this.#buffer; this.#buffer = []; try { for (const result of this.#db.upsertDocuments(batch)) { if (result.changed) this.#counters.indexed++; else this.#counters.unchanged++; } } catch (err) { this.#log(`Buffer flush error: ${err}`); } finally { for (const doc of batch) this.#bufferedSimhashes.delete(doc.url); } } async #closePools(): Promise { for (const [key, pool] of this.#pools) { const tier = key.split("|")[0] as string; this.#counters.pagesCreated[tier] = (this.#counters.pagesCreated[tier] ?? 0) + pool.stats().created; } await Promise.all([...this.#pools.values()].map((pool) => pool.close())); this.#pools.clear(); } stop(): void { this.#isRunning = false; this.#crawler?.stop(); if (this.#recoveryTimer) clearInterval(this.#recoveryTimer); void this.#flushBuffer(); } stats(): MassiveCrawlerStats { const pagesCreated: Record = { ...this.#counters.pagesCreated }; for (const [key, pool] of this.#pools) { const tier = key.split("|")[0] as string; pagesCreated[tier] = (pagesCreated[tier] ?? 0) + pool.stats().created; } return { queue: this.#requestQueue.stats(), buffered: this.#buffer.length, ...this.#counters, tierAttempts: { ...this.#counters.tierAttempts }, pagesCreated, }; } /** `true` if `url` was (probably) enqueued before, in this or a previous run. */ hasSeen(url: string): boolean { return this.#seen.has(this.#canonicalKey(url)); } /** Underlying index (read access for callers and tests). */ get db(): BxcDB { return this.#db; } }