Commit | Line | Data |
---|---|---|
edd13439 | 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
c8eeb62b | 2 | |
a679a162 | 3 | import { AsyncResource } from 'node:async_hooks'; |
6b57eb9a | 4 | import { parentPort } from 'node:worker_threads'; |
8114d10e JB |
5 | |
6 | import { ThreadWorker } from 'poolifier'; | |
7 | ||
4c3c0d59 | 8 | import { ChargingStation } from './ChargingStation'; |
268a74bb | 9 | import type { ChargingStationWorkerData } from '../types'; |
a4e5c2e2 | 10 | import { Configuration } from '../utils'; |
268a74bb | 11 | import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker'; |
7dde0b73 | 12 | |
e8a92d57 JB |
13 | /** |
14 | * Create and start a charging station instance | |
15 | * | |
16 | * @param data - workerData | |
17 | */ | |
18 | const startChargingStation = (data: ChargingStationWorkerData): void => { | |
a679a162 | 19 | new ChargingStation(data.index, data.templateFile).start(); |
e8a92d57 JB |
20 | }; |
21 | ||
6b57eb9a JB |
22 | class ChargingStationWorker extends AsyncResource { |
23 | constructor() { | |
24 | super('ChargingStationWorker'); | |
25 | // Add message listener to create and start charging station from the main thread | |
26 | parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => { | |
27 | if (message.id === WorkerMessageEvents.startWorkerElement) { | |
28 | this.run(message.data); | |
29 | } | |
30 | }); | |
31 | } | |
32 | ||
33 | private run(data: ChargingStationWorkerData): void { | |
34 | this.runInAsyncScope( | |
35 | startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, | |
36 | this, | |
37 | data | |
38 | ); | |
39 | } | |
40 | } | |
41 | ||
42 | export let chargingStationWorker: ChargingStationWorker; | |
b8da29bc | 43 | // Conditionally export ThreadWorker instance for pool usage |
56a74dae | 44 | export let threadWorker: ThreadWorker; |
aa7d6d95 | 45 | if (Configuration.workerPoolInUse()) { |
e7aeea18 | 46 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
3fa0f0ed | 47 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
e7aeea18 | 48 | }); |
74bbc59b | 49 | } else { |
6b57eb9a | 50 | chargingStationWorker = new ChargingStationWorker(); |
3d2ff9e4 | 51 | } |