()
| 44 | } |
| 45 | |
| 46 | private async startWorker(): Promise<void> { |
| 47 | const wrapperPath = path.join(getWrapperDir('python'), 'persistent_wrapper.py'); |
| 48 | |
| 49 | // Validate and resolve Python path using smart detection (tries python3, then python) |
| 50 | const resolvedPythonPath = await validatePythonPath( |
| 51 | this.pythonPath || 'python', |
| 52 | typeof this.pythonPath === 'string', |
| 53 | ); |
| 54 | |
| 55 | this.process = new PythonShell(wrapperPath, { |
| 56 | mode: 'text', |
| 57 | pythonPath: resolvedPythonPath, |
| 58 | args: [this.scriptPath, this.functionName], |
| 59 | stdio: ['pipe', 'pipe', 'pipe'], |
| 60 | }); |
| 61 | |
| 62 | // Listen for READY signal |
| 63 | return new Promise((resolve, reject) => { |
| 64 | const readyTimeout = setTimeout(() => { |
| 65 | // Kill the process to prevent orphaned Python processes |
| 66 | // and avoid triggering handleCrash() which would retry |
| 67 | this.shuttingDown = true; |
| 68 | if (this.process) { |
| 69 | this.process.kill('SIGTERM'); |
| 70 | this.process = null; |
| 71 | } |
| 72 | reject(new Error('Worker failed to become ready within timeout')); |
| 73 | }, 30000); |
| 74 | |
| 75 | this.process!.on('message', (message: string) => { |
| 76 | if (message.trim() === 'READY') { |
| 77 | clearTimeout(readyTimeout); |
| 78 | this.ready = true; |
| 79 | logger.debug(`Python worker ready for ${this.scriptPath}`); |
| 80 | // Notify pool that worker is ready (triggers queue processing) |
| 81 | if (this.onReady) { |
| 82 | this.onReady(); |
| 83 | } |
| 84 | resolve(); |
| 85 | } else if (message.startsWith('DONE|')) { |
| 86 | this.handleDone(message.slice('DONE|'.length)); |
| 87 | } |
| 88 | }); |
| 89 | |
| 90 | this.process!.on('error', (err) => { |
| 91 | clearTimeout(readyTimeout); |
| 92 | reject(err); |
| 93 | }); |
| 94 | |
| 95 | this.process!.on('close', () => { |
| 96 | this.flushStderr(); |
| 97 | if (!this.shuttingDown) { |
| 98 | this.handleCrash(); |
| 99 | } |
| 100 | }); |
| 101 | |
| 102 | this.process!.stderr?.on('data', (data) => { |
| 103 | this.handleStderr(data); |
no test coverage detected