/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/ffi/curl-worker-pool * * Runs libcurl-impersonate requests on worker threads so the blocking * `curl_easy_perform` never stalls the JavaScript event loop (MCP requests, * timers, concurrent crawl tasks and in-process servers keep running). * * Routing is sticky per client key: a client's requests always go to the same * worker, preserving keep-alive connections and the single-easy-handle * semantics of `ImpersonatedClient`. New clients go to the least-loaded * worker. Pool size: `BXC_CURL_WORKERS` (default: 2 × cores, clamped 4–32). */ import type { FetchOptions, ImpersonatedClientOptions } from "./curl-impersonate.ts"; /** Structured-clone-safe subset of `FetchOptions`. */ export type SerializableFetchOptions = Omit & { headers?: Record; body?: string | Uint8Array; }; export type CurlWorkerRequest = | { type: "fetch"; id: number; clientKey: string; clientOptions: ImpersonatedClientOptions; url: string; options: SerializableFetchOptions; } | { type: "close"; clientKey: string }; export type CurlWorkerResponse = | { type: "ready" } | { type: "response"; id: number; status: number; statusText: string; headers: Array<[string, string]>; url: string; body: ArrayBuffer; } | { type: "error"; id: number; message: string; curlCode: number | null }; export interface CurlWorkerResult { status: number; statusText: string; headers: Array<[string, string]>; url: string; body: ArrayBuffer; } export class CurlWorkerError extends Error { readonly curlCode: number | null; constructor(message: string, curlCode: number | null) { super(message); this.name = "CurlWorkerError"; this.curlCode = curlCode; } } interface Pending { resolve: (result: CurlWorkerResult) => void; reject: (error: Error) => void; worker: WorkerSlot; } /** Bun workers can be (un)referenced like timers; the DOM typings omit it. */ type RefableWorker = Worker & { ref(): void; unref(): void }; interface WorkerSlot { worker: RefableWorker; inflight: number; clients: number; } function defaultPoolSize(): number { const fromEnv = Number(Bun.env.BXC_CURL_WORKERS); if (Number.isFinite(fromEnv) && fromEnv > 0) return Math.floor(fromEnv); const cores = navigator.hardwareConcurrency || 4; return Math.min(32, Math.max(4, cores * 2)); } const READY_TIMEOUT_MS = 10_000; export class CurlWorkerPool { readonly size: number; readonly #slots: WorkerSlot[] = []; readonly #pending = new Map(); readonly #affinity = new Map(); #nextId = 1; #ready: Promise | null = null; #failed: Error | null = null; constructor(size = defaultPoolSize()) { this.size = Math.max(1, size); } /** Start workers once; rejects if a worker cannot load the curl binding. */ start(): Promise { this.#ready ??= this.#spawnAll().catch((err) => { this.#failed = err instanceof Error ? err : new Error(String(err)); this.terminate(); throw this.#failed; }); return this.#ready; } get failed(): Error | null { return this.#failed; } async #spawnAll(): Promise { const entry = new URL("./curl-worker.ts", import.meta.url).href; await Promise.all( Array.from({ length: this.size }, async () => { const worker = new Worker(entry) as RefableWorker; const slot: WorkerSlot = { worker, inflight: 0, clients: 0 }; this.#slots.push(slot); await new Promise((resolve, reject) => { const timer = setTimeout( () => reject(new Error("curl worker did not become ready")), READY_TIMEOUT_MS, ); worker.addEventListener("error", (event) => { clearTimeout(timer); reject(new Error(`curl worker failed: ${(event as ErrorEvent).message}`)); }); worker.addEventListener("message", (event: MessageEvent) => { if (event.data.type === "ready") { clearTimeout(timer); resolve(); return; } this.#onMessage(event.data); }); }); // Idle workers must not keep the process alive. worker.unref(); }), ); } #onMessage(message: CurlWorkerResponse): void { if (message.type === "ready") return; const pending = this.#pending.get(message.id); if (!pending) return; this.#pending.delete(message.id); pending.worker.inflight--; if (pending.worker.inflight === 0) pending.worker.worker.unref(); if (message.type === "error") { pending.reject(new CurlWorkerError(message.message, message.curlCode)); } else { pending.resolve({ status: message.status, statusText: message.statusText, headers: message.headers, url: message.url, body: message.body, }); } } #slotFor(clientKey: string): WorkerSlot { const existing = this.#affinity.get(clientKey); if (existing) return existing; let best = this.#slots[0] as WorkerSlot; for (const slot of this.#slots) { if (slot.clients < best.clients || (slot.clients === best.clients && slot.inflight < best.inflight)) { best = slot; } } best.clients++; this.#affinity.set(clientKey, best); return best; } async fetch( clientKey: string, clientOptions: ImpersonatedClientOptions, url: string, options: SerializableFetchOptions, signal?: AbortSignal, ): Promise { await this.start(); signal?.throwIfAborted(); const slot = this.#slotFor(clientKey); const id = this.#nextId++; return new Promise((resolve, reject) => { const onAbort = () => { // The worker finishes the transfer; the caller stops waiting. if (this.#pending.has(id)) { this.#pending.get(id)!.reject(signal!.reason ?? new DOMException("Aborted", "AbortError")); } }; this.#pending.set(id, { resolve: (value) => { signal?.removeEventListener("abort", onAbort); resolve(value); }, reject: (error) => { signal?.removeEventListener("abort", onAbort); reject(error); }, worker: slot, }); signal?.addEventListener("abort", onAbort, { once: true }); if (slot.inflight === 0) slot.worker.ref(); slot.inflight++; slot.worker.postMessage({ type: "fetch", id, clientKey, clientOptions, url, options, } satisfies CurlWorkerRequest); }); } /** Release the worker-side client for `clientKey`. */ closeClient(clientKey: string): void { const slot = this.#affinity.get(clientKey); if (!slot) return; this.#affinity.delete(clientKey); slot.clients--; slot.worker.postMessage({ type: "close", clientKey } satisfies CurlWorkerRequest); } terminate(): void { for (const slot of this.#slots) slot.worker.terminate(); this.#slots.length = 0; this.#affinity.clear(); for (const pending of this.#pending.values()) { pending.reject(new Error("curl worker pool terminated")); } this.#pending.clear(); } } let sharedPool: CurlWorkerPool | null = null; /** Process-wide pool used by `ImpersonatedClient` on the main thread. */ export function sharedCurlWorkerPool(): CurlWorkerPool { sharedPool ??= new CurlWorkerPool(); return sharedPool; }