import { Worker, receiveMessageOnPort, MessageChannel } from "node:worker_threads"; import { fileURLToPath } from "node:url"; const workerMainPath = fileURLToPath(new URL("./threadWorkerMain.js", import.meta.url)); export class ThreadWorker { constructor (workerId) { this.workerId = workerId; this.sync = new Int32Array(new SharedArrayBuffer(4)); this.worker = new Worker(workerMainPath, { workerData: { workerId, sync: this.sync.buffer } }); this.worker.on("error", (error) => { this.error = error; }); } call (message) { if (this.error) { throw this.error; } const { port1, port2 } = new MessageChannel(); Atomics.store(this.sync, 0, 0); this.worker.postMessage({ message, port: port2 }, [port2]); const status = Atomics.wait(this.sync, 0, 0, 10_000); if (status === "timed-out") { port1.close(); throw new Error(`Simulation worker ${this.workerId} timed out.`); } const received = receiveMessageOnPort(port1); port1.close(); if (this.error) { throw this.error; } if (!received) { throw new Error(`Simulation worker ${this.workerId} returned no result.`); } const result = received.message; if (result?.__error) { const error = new Error(result.__error.message); error.userFacing = result.__error.userFacing; throw error; } return result; } async terminate () { await this.worker.terminate(); } }