| 1 | import { Worker } from "node:worker_threads"; |
| 2 | import type { CpuProfile, ProfileFrame } from "./rendererDiagnostics.js"; |
| 3 | |
| 4 | export function analyseInWorker(profile: CpuProfile, workerPath: string): Promise<ProfileFrame[]> { |
| 5 | if (profile.nodes.length > 20_000 || (profile.samples?.length ?? 0) > 100_000) return Promise.reject(new Error("profile exceeds analysis budget")); |
| 6 | return new Promise((resolve, reject) => { |
| 7 | const worker = new Worker(workerPath, { workerData: profile, resourceLimits: { maxOldGenerationSizeMb: 32 } }); |
| 8 | const timer = setTimeout(() => finish(new Error("profile analysis timeout")), 1500); |
| 9 | let settled = false; |
| 10 | const finish = (error?: Error, frames?: ProfileFrame[]) => { |
| 11 | if (settled) return; |
| 12 | settled = true; |
| 13 | clearTimeout(timer); |
| 14 | void worker.terminate(); |
| 15 | if (error) reject(error); else resolve(frames ?? []); |
| 16 | }; |
| 17 | worker.once("message", (frames: ProfileFrame[]) => finish(undefined, frames)); |
| 18 | worker.once("error", (error) => finish(error instanceof Error ? error : new Error("profile analysis failed"))); |
| 19 | worker.once("exit", () => finish(new Error("profile analysis exited without a result"))); |
| 20 | }); |
| 21 | } |
| 22 |