| 1 | import { Worker, receiveMessageOnPort, MessageChannel } from "node:worker_threads"; |
| 2 | import { fileURLToPath } from "node:url"; |
| 3 | |
| 4 | const workerMainPath = fileURLToPath(new URL("./threadWorkerMain.js", import.meta.url)); |
| 5 | |
| 6 | export class ThreadWorker |
| 7 | { |
| 8 | constructor (workerId) |
| 9 | { |
| 10 | this.workerId = workerId; |
| 11 | this.sync = new Int32Array(new SharedArrayBuffer(4)); |
| 12 | this.worker = new Worker(workerMainPath, { |
| 13 | workerData: { workerId, sync: this.sync.buffer } |
| 14 | }); |
| 15 | this.worker.on("error", (error) => |
| 16 | { |
| 17 | this.error = error; |
| 18 | }); |
| 19 | } |
| 20 | |
| 21 | call (message) |
| 22 | { |
| 23 | if (this.error) |
| 24 | { throw this.error; } |
| 25 | const { port1, port2 } = new MessageChannel(); |
| 26 | Atomics.store(this.sync, 0, 0); |
| 27 | this.worker.postMessage({ message, port: port2 }, [port2]); |
| 28 | const status = Atomics.wait(this.sync, 0, 0, 10_000); |
| 29 | if (status === "timed-out") |
| 30 | { |
| 31 | port1.close(); |
| 32 | throw new Error(`Simulation worker ${this.workerId} timed out.`); |
| 33 | } |
| 34 | const received = receiveMessageOnPort(port1); |
| 35 | port1.close(); |
| 36 | if (this.error) |
| 37 | { throw this.error; } |
| 38 | if (!received) |
| 39 | { throw new Error(`Simulation worker ${this.workerId} returned no result.`); } |
| 40 | const result = received.message; |
| 41 | if (result?.__error) |
| 42 | { |
| 43 | const error = new Error(result.__error.message); |
| 44 | error.userFacing = result.__error.userFacing; |
| 45 | throw error; |
| 46 | } |
| 47 | return result; |
| 48 | } |
| 49 | |
| 50 | async terminate () |
| 51 | { |
| 52 | await this.worker.terminate(); |
| 53 | } |
| 54 | } |