|
| 1 | +import { spawn } from 'node:child_process'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { fileURLToPath } from 'node:url'; |
| 4 | +import { NodejsProfiler } from '../../src/lib/profiler/profiler-node.js'; |
| 5 | +import { entryToTraceEvents } from '../../src/lib/profiler/trace-file-utils.js'; |
| 6 | +import { traceEventWalFormat } from '../../src/lib/profiler/wal-json-trace.js'; |
| 7 | + |
| 8 | +const [numProcesses] = process.argv.slice(2); |
| 9 | + |
| 10 | +if (!numProcesses) { |
| 11 | + console.error('Usage: node profiler-worker.mjs <numProcesses>'); |
| 12 | + process.exit(1); |
| 13 | +} |
| 14 | + |
| 15 | +const numProcs = parseInt(numProcesses, 10); |
| 16 | +if (isNaN(numProcs) || numProcs < 1) { |
| 17 | + console.error('numProcesses must be a positive integer'); |
| 18 | + process.exit(1); |
| 19 | +} |
| 20 | + |
| 21 | +const workerScriptPath = path.join( |
| 22 | + fileURLToPath(path.dirname(import.meta.url)), |
| 23 | + './profiler-worker-child.mjs', |
| 24 | +); |
| 25 | + |
| 26 | +const profiler = new NodejsProfiler({ |
| 27 | + format: { |
| 28 | + ...traceEventWalFormat(), |
| 29 | + encodePerfEntry: entryToTraceEvents, |
| 30 | + }, |
| 31 | +}); |
| 32 | + |
| 33 | +(async () => { |
| 34 | + const processes = Array.from({ length: numProcs }, (_, i) => { |
| 35 | + return new Promise((resolve, reject) => { |
| 36 | + const child = spawn('npx', ['tsx', workerScriptPath], { |
| 37 | + stdio: 'pipe', |
| 38 | + }); |
| 39 | + |
| 40 | + child.on('close', code => { |
| 41 | + if (code === 0) { |
| 42 | + resolve(code); |
| 43 | + } else { |
| 44 | + reject(new Error(`Process ${i + 1} exited with code ${code}`)); |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + child.on('error', reject); |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + await Promise.all(processes); |
| 53 | + |
| 54 | + profiler.close(); |
| 55 | + console.log(JSON.stringify(profiler.stats, null, 2)); |
| 56 | +})(); |
0 commit comments