/** * 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/WorkerPool * * High-performance persistent worker pool for multi-worker browser crawling. * Reuses long-lived Bun Worker isolates instead of spawning a new worker per request. */ export interface WorkerTask { request: any; options: any; handlerCode?: string; handlerPath?: string; resolve: () => void; reject: (err: Error) => void; pendingWrites: Set>; } export interface WorkerPoolOptions { minWorkers?: number; maxWorkers?: number; workerScriptUrl?: string; onPushData?: (data: any) => Promise; onAddRequests?: (urls: any[]) => void; onLog?: (msg: string) => void; } interface ManagedWorker { worker: Worker; busy: boolean; currentTask: WorkerTask | null; } export class WorkerPool { readonly #minWorkers: number; readonly #maxWorkers: number; readonly #workerUrl: string; readonly #onPushData?: (data: any) => Promise; readonly #onAddRequests?: (urls: any[]) => void; readonly #onLog?: (msg: string) => void; #workers: ManagedWorker[] = []; #queue: WorkerTask[] = []; #closed = false; constructor(options: WorkerPoolOptions = {}) { this.#minWorkers = Math.max(1, options.minWorkers ?? 2); this.#maxWorkers = Math.max(this.#minWorkers, options.maxWorkers ?? 20); this.#workerUrl = options.workerScriptUrl ?? new URL("./BrowserWorker.ts", import.meta.url).href; this.#onPushData = options.onPushData; this.#onAddRequests = options.onAddRequests; this.#onLog = options.onLog; // Pre-warm minimum workers for (let i = 0; i < this.#minWorkers; i++) { this.#spawnWorker(); } } #spawnWorker(): ManagedWorker { const worker = new Worker(this.#workerUrl); (worker as any).unref(); const managed: ManagedWorker = { worker, busy: false, currentTask: null, }; worker.onmessage = async (event: MessageEvent) => { const { type, data, urls, message, error } = event.data; const task = managed.currentTask; if (type === "pushData") { if (this.#onPushData && task) { const write = this.#onPushData(data); task.pendingWrites.add(write); try { await write; } finally { task.pendingWrites.delete(write); } } } else if (type === "addRequests") { this.#onAddRequests?.(urls); } else if (type === "log") { this.#onLog?.(message); } else if (type === "done") { if (task) { await Promise.all(task.pendingWrites); managed.busy = false; managed.currentTask = null; task.resolve(); this.#processNext(); } } else if (type === "error") { if (task) { managed.busy = false; managed.currentTask = null; task.reject(new Error(error || "Worker task execution error")); this.#processNext(); } } }; worker.onerror = (err) => { const task = managed.currentTask; this.#removeWorker(managed); if (task) { task.reject(err instanceof Error ? err : new Error(String(err))); } // Respawn replacement worker if pool is still open if (!this.#closed && this.#workers.length < this.#minWorkers) { this.#spawnWorker(); } this.#processNext(); }; this.#workers.push(managed); return managed; } #removeWorker(managed: ManagedWorker): void { try { managed.worker.terminate(); } catch {} const idx = this.#workers.indexOf(managed); if (idx !== -1) { this.#workers.splice(idx, 1); } } #processNext(): void { if (this.#closed || this.#queue.length === 0) return; // Find an idle worker let idle = this.#workers.find((w) => !w.busy); // If no idle worker and we can scale up, spawn a new one if (!idle && this.#workers.length < this.#maxWorkers) { idle = this.#spawnWorker(); } if (!idle) return; const task = this.#queue.shift(); if (!task) return; idle.busy = true; idle.currentTask = task; idle.worker.postMessage({ type: "crawl", id: task.request.id, url: task.request.url, method: task.request.method, payload: task.request.payload, headers: task.request.headers, userData: task.request.userData, options: task.options, handlerCode: task.handlerCode, handlerPath: task.handlerPath, }); } /** * Dispatches a crawl request to an available worker in the pool. */ dispatch( request: any, options: any, handlerCode?: string, handlerPath?: string, ): Promise { if (this.#closed) { return Promise.reject(new Error("WorkerPool is closed")); } return new Promise((resolve, reject) => { const task: WorkerTask = { request, options, handlerCode, handlerPath, resolve, reject, pendingWrites: new Set(), }; this.#queue.push(task); this.#processNext(); }); } /** * Wait until all queued and running tasks are completed. */ async drain(): Promise { while (this.#queue.length > 0 || this.#workers.some((w) => w.busy)) { await Bun.sleep(50); } } /** * Terminate all workers in the pool and release resources. */ terminate(): void { this.#closed = true; for (const task of this.#queue) { task.reject(new Error("WorkerPool terminated")); } this.#queue.length = 0; for (const w of this.#workers) { try { w.worker.terminate(); } catch {} } this.#workers.length = 0; } stats(): { total: number; busy: number; idle: number; queued: number } { const busy = this.#workers.filter((w) => w.busy).length; return { total: this.#workers.length, busy, idle: this.#workers.length - busy, queued: this.#queue.length, }; } }