| 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
| 2 | |
| 3 | import { AsyncResource } from 'node:async_hooks'; |
| 4 | import { parentPort } from 'node:worker_threads'; |
| 5 | |
| 6 | import { ThreadWorker } from 'poolifier'; |
| 7 | |
| 8 | import { ChargingStation } from './ChargingStation'; |
| 9 | import type { ChargingStationWorkerData } from '../types'; |
| 10 | import { Configuration } from '../utils'; |
| 11 | import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker'; |
| 12 | |
| 13 | const moduleName = 'ChargingStationWorker'; |
| 14 | |
| 15 | /** |
| 16 | * Creates and starts a charging station instance |
| 17 | * |
| 18 | * @param data - workerData |
| 19 | */ |
| 20 | const startChargingStation = (data?: ChargingStationWorkerData): void => { |
| 21 | new ChargingStation(data!.index, data!.templateFile).start(); |
| 22 | }; |
| 23 | |
| 24 | class ChargingStationWorker extends AsyncResource { |
| 25 | constructor() { |
| 26 | super(moduleName); |
| 27 | // Add message listener to create and start charging station from the main thread |
| 28 | parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => { |
| 29 | switch (message.event) { |
| 30 | case WorkerMessageEvents.startWorkerElement: |
| 31 | try { |
| 32 | this.runInAsyncScope( |
| 33 | startChargingStation.bind(this) as (data?: ChargingStationWorkerData) => void, |
| 34 | this, |
| 35 | message.data, |
| 36 | ); |
| 37 | parentPort?.postMessage({ |
| 38 | event: WorkerMessageEvents.startedWorkerElement, |
| 39 | }); |
| 40 | } catch (error) { |
| 41 | parentPort?.postMessage({ |
| 42 | event: WorkerMessageEvents.startWorkerElementError, |
| 43 | data: { |
| 44 | message: (error as Error).message, |
| 45 | stack: (error as Error).stack, |
| 46 | }, |
| 47 | }); |
| 48 | } |
| 49 | break; |
| 50 | default: |
| 51 | throw new Error( |
| 52 | `Unknown worker event: '${message.event}' received with data: '${JSON.stringify( |
| 53 | message.data, |
| 54 | null, |
| 55 | 2, |
| 56 | )}'`, |
| 57 | ); |
| 58 | } |
| 59 | }); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | export let chargingStationWorker: ChargingStationWorker | ThreadWorker<ChargingStationWorkerData>; |
| 64 | if (Configuration.workerPoolInUse()) { |
| 65 | chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
| 66 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
| 67 | }); |
| 68 | } else { |
| 69 | chargingStationWorker = new ChargingStationWorker(); |
| 70 | } |