]>
Commit | Line | Data |
---|---|---|
1 | // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved. | |
2 | ||
3 | import { parentPort } from 'node:worker_threads' | |
4 | import { ThreadWorker } from 'poolifier' | |
5 | ||
6 | import type { ChargingStationInfo, ChargingStationWorkerData } from '../types/index.js' | |
7 | ||
8 | import { BaseError } from '../exception/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, options, templateFile } = 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 { data, event, uuid } = 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 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
41 | data: chargingStation.stationInfo!, | |
42 | event: WorkerMessageEvents.addedWorkerElement, | |
43 | uuid, | |
44 | } satisfies WorkerMessage<ChargingStationInfo>) | |
45 | } catch (error) { | |
46 | parentPort?.postMessage({ | |
47 | data: { | |
48 | event, | |
49 | message: (error as Error).message, | |
50 | name: (error as Error).name, | |
51 | stack: (error as Error).stack, | |
52 | }, | |
53 | event: WorkerMessageEvents.workerElementError, | |
54 | uuid, | |
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 | } |