]>
Commit | Line | Data |
---|---|---|
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 | * Create and start 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 | if (message.id === WorkerMessageEvents.startWorkerElement) { | |
30 | this.runInAsyncScope( | |
31 | startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, | |
32 | this, | |
33 | message.data | |
34 | ); | |
35 | } | |
36 | }); | |
37 | } | |
38 | } | |
39 | ||
40 | export let chargingStationWorker: ChargingStationWorker; | |
41 | // Conditionally export ThreadWorker instance for pool usage | |
42 | export let threadWorker: ThreadWorker; | |
43 | if (Configuration.workerPoolInUse()) { | |
44 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { | |
45 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, | |
46 | }); | |
47 | } else { | |
48 | chargingStationWorker = new ChargingStationWorker(); | |
49 | } |