| 9 | } |
| 10 | |
| 11 | export class PythonWorkerPool { |
| 12 | private workers: PythonWorker[] = []; |
| 13 | private queue: QueuedRequest[] = []; |
| 14 | private isInitialized: boolean = false; |
| 15 | |
| 16 | constructor( |
| 17 | private scriptPath: string, |
| 18 | private functionName: string, |
| 19 | private workerCount: number = 1, |
| 20 | private pythonPath?: string, |
| 21 | private timeout?: number, |
| 22 | ) {} |
| 23 | |
| 24 | async initialize(): Promise<void> { |
| 25 | if (this.isInitialized) { |
| 26 | return; |
| 27 | } |
| 28 | |
| 29 | // Validate worker count |
| 30 | if (this.workerCount < 1) { |
| 31 | throw new Error(`Invalid worker count: ${this.workerCount}. Must be at least 1.`); |
| 32 | } |
| 33 | |
| 34 | // Warn on excessive workers |
| 35 | if (this.workerCount > 8) { |
| 36 | logger.warn( |
| 37 | `Spawning ${this.workerCount} Python workers for ${this.scriptPath}. ` + |
| 38 | `This may use significant memory if your script has heavy imports.`, |
| 39 | ); |
| 40 | } |
| 41 | |
| 42 | logger.debug( |
| 43 | `Initializing Python worker pool with ${this.workerCount} workers for ${this.scriptPath}`, |
| 44 | ); |
| 45 | |
| 46 | // Start all workers in parallel |
| 47 | const initPromises = []; |
| 48 | for (let i = 0; i < this.workerCount; i++) { |
| 49 | const worker = new PythonWorker( |
| 50 | this.scriptPath, |
| 51 | this.functionName, |
| 52 | this.pythonPath, |
| 53 | this.timeout, |
| 54 | () => this.processQueue(), // Resume queue processing when worker becomes ready |
| 55 | ); |
| 56 | initPromises.push(worker.initialize()); |
| 57 | this.workers.push(worker); |
| 58 | } |
| 59 | |
| 60 | await Promise.all(initPromises); |
| 61 | this.isInitialized = true; |
| 62 | logger.debug(`Python worker pool initialized with ${this.workerCount} workers`); |
| 63 | } |
| 64 | |
| 65 | // biome-ignore lint/suspicious/noExplicitAny: FIXME |
| 66 | async execute(functionName: string, args: unknown[]): Promise<any> { |
| 67 | if (!this.isInitialized) { |
| 68 | throw new Error('Worker pool not initialized'); |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…