| 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 { ChargingStation } from './ChargingStation.js' |
| 8 | import { BaseError } from '../exception/index.js' |
| 9 | import type { ChargingStationWorkerData } from '../types/index.js' |
| 10 | import { Configuration } from '../utils/index.js' |
| 11 | import { type WorkerMessage, WorkerMessageEvents } from '../worker/index.js' |
| 12 | |
| 13 | /** |
| 14 | * Creates and starts a charging station instance |
| 15 | * |
| 16 | * @param data - data sent to worker |
| 17 | */ |
| 18 | const startChargingStation = (data?: ChargingStationWorkerData): void => { |
| 19 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 20 | new ChargingStation(data!.index, data!.templateFile).start() |
| 21 | } |
| 22 | |
| 23 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class |
| 24 | class ChargingStationWorker<Data extends ChargingStationWorkerData> { |
| 25 | constructor () { |
| 26 | // Add message listener to create and start charging station from the main thread |
| 27 | parentPort?.on('message', (message: WorkerMessage<Data>) => { |
| 28 | switch (message.event) { |
| 29 | case WorkerMessageEvents.startWorkerElement: |
| 30 | try { |
| 31 | startChargingStation(message.data) |
| 32 | parentPort?.postMessage({ |
| 33 | event: WorkerMessageEvents.startedWorkerElement |
| 34 | }) |
| 35 | } catch (error) { |
| 36 | parentPort?.postMessage({ |
| 37 | event: WorkerMessageEvents.startWorkerElementError, |
| 38 | data: { |
| 39 | name: (error as Error).name, |
| 40 | message: (error as Error).message, |
| 41 | stack: (error as Error).stack |
| 42 | } |
| 43 | }) |
| 44 | } |
| 45 | break |
| 46 | default: |
| 47 | throw new BaseError( |
| 48 | `Unknown worker event: '${message.event}' received with data: '${JSON.stringify( |
| 49 | message.data, |
| 50 | undefined, |
| 51 | 2 |
| 52 | )}'` |
| 53 | ) |
| 54 | } |
| 55 | }) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export let chargingStationWorker: |
| 60 | | ChargingStationWorker<ChargingStationWorkerData> |
| 61 | | ThreadWorker<ChargingStationWorkerData> |
| 62 | if (Configuration.workerPoolInUse()) { |
| 63 | chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation) |
| 64 | } else { |
| 65 | chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>() |
| 66 | } |