| 1 | // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved. |
| 2 | |
| 3 | import { parentPort } from 'node:worker_threads' |
| 4 | |
| 5 | import { ThreadWorker } from 'poolifier' |
| 6 | |
| 7 | import { BaseError } from '../exception/index.js' |
| 8 | import type { ChargingStationInfo, ChargingStationWorkerData } from '../types/index.js' |
| 9 | import { Configuration } from '../utils/index.js' |
| 10 | import { type WorkerDataError, type WorkerMessage, WorkerMessageEvents } from '../worker/index.js' |
| 11 | import { ChargingStation } from './ChargingStation.js' |
| 12 | |
| 13 | export let chargingStationWorker: object |
| 14 | if (Configuration.workerPoolInUse()) { |
| 15 | chargingStationWorker = new ThreadWorker< |
| 16 | ChargingStationWorkerData, |
| 17 | ChargingStationInfo | undefined |
| 18 | >((data?: ChargingStationWorkerData): ChargingStationInfo | undefined => { |
| 19 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 20 | const { index, templateFile, options } = data! |
| 21 | return new ChargingStation(index, templateFile, options).stationInfo |
| 22 | }) |
| 23 | } else { |
| 24 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class |
| 25 | class ChargingStationWorker<Data extends ChargingStationWorkerData> { |
| 26 | constructor () { |
| 27 | parentPort?.on('message', (message: WorkerMessage<Data>) => { |
| 28 | const { uuid, event, data } = message |
| 29 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 30 | if (uuid != null) { |
| 31 | switch (event) { |
| 32 | case WorkerMessageEvents.addWorkerElement: |
| 33 | try { |
| 34 | const chargingStation = new ChargingStation( |
| 35 | data.index, |
| 36 | data.templateFile, |
| 37 | data.options |
| 38 | ) |
| 39 | parentPort?.postMessage({ |
| 40 | uuid, |
| 41 | event: WorkerMessageEvents.addedWorkerElement, |
| 42 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 43 | data: chargingStation.stationInfo! |
| 44 | } satisfies WorkerMessage<ChargingStationInfo>) |
| 45 | } catch (error) { |
| 46 | parentPort?.postMessage({ |
| 47 | uuid, |
| 48 | event: WorkerMessageEvents.workerElementError, |
| 49 | data: { |
| 50 | event, |
| 51 | name: (error as Error).name, |
| 52 | message: (error as Error).message, |
| 53 | stack: (error as Error).stack |
| 54 | } |
| 55 | } satisfies WorkerMessage<WorkerDataError>) |
| 56 | } |
| 57 | break |
| 58 | default: |
| 59 | throw new BaseError( |
| 60 | `Unknown worker message event: '${event}' received with data: '${JSON.stringify( |
| 61 | data, |
| 62 | undefined, |
| 63 | 2 |
| 64 | )}'` |
| 65 | ) |
| 66 | } |
| 67 | } |
| 68 | }) |
| 69 | } |
| 70 | } |
| 71 | chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>() |
| 72 | } |