(timeoutMs: number)
| 7 | /** Local subprocess execution, not a security sandbox. Requires python3 and pandas. */ |
| 8 | export const createPythonExecutor = |
| 9 | (timeoutMs: number) => |
| 10 | async (code: string, maxBuffer: number, signal?: AbortSignal): Promise<ExecutionResult> => { |
| 11 | throwIfAborted(signal); |
| 12 | const pending = new Promise<ExecutionResult>((resolve, reject) => { |
| 13 | let inputError: Error | undefined; |
| 14 | let detach: (() => void) | undefined; |
| 15 | const child = execFile( |
| 16 | 'python3', |
| 17 | ['-'], |
| 18 | { |
| 19 | timeout: timeoutMs, |
| 20 | killSignal: 'SIGKILL', |
| 21 | maxBuffer, |
| 22 | encoding: 'utf8', |
| 23 | }, |
| 24 | (error, stdout, stderr) => { |
| 25 | detach?.(); |
| 26 | const failure = error ?? inputError; |
| 27 | if (failure) { |
| 28 | reject( |
| 29 | new Error(`Python execution failed (requires python3 and pandas): ${stderr.trim() || failure.message}`) |
| 30 | ); |
| 31 | return; |
| 32 | } |
| 33 | try { |
| 34 | resolve(JSON.parse(stdout)); |
| 35 | } catch { |
| 36 | reject(new Error('Python returned an invalid JSON result')); |
| 37 | } |
| 38 | } |
| 39 | ); |
| 40 | // Kill explicitly so cancellation uses SIGKILL and execFile waits for the child and its pipes to close. |
| 41 | const terminate = () => { |
| 42 | child.stdout?.destroy(); |
| 43 | child.stderr?.destroy(); |
| 44 | if (!child.killed) child.kill('SIGKILL'); |
| 45 | }; |
| 46 | detach = onAbort(signal, terminate); |
| 47 | child.stdin!.on('error', (error) => { |
| 48 | inputError = error; |
| 49 | terminate(); |
| 50 | }); |
| 51 | child.stdin!.end(code); |
| 52 | }); |
| 53 | try { |
| 54 | const result = await pending; |
| 55 | throwIfAborted(signal); |
| 56 | return result; |
| 57 | } catch (error) { |
| 58 | throwIfAborted(signal); |
| 59 | throw error; |
| 60 | } |
| 61 | }; |
no test coverage detected