1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import path from
'node:path';
4 import { fileURLToPath
} from
'node:url';
5 import { type Worker
, isMainThread
} from
'worker_threads';
7 import chalk from
'chalk';
9 import { ChargingStationUtils
} from
'./ChargingStationUtils';
10 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
11 import UIServerFactory from
'./ui-server/UIServerFactory';
12 import { version
} from
'../../package.json';
13 import BaseError from
'../exception/BaseError';
14 import type { Storage
} from
'../performance/storage/Storage';
15 import { StorageFactory
} from
'../performance/storage/StorageFactory';
17 type ChargingStationData
,
18 type ChargingStationWorkerData
,
19 type ChargingStationWorkerMessage
,
20 type ChargingStationWorkerMessageData
,
21 ChargingStationWorkerMessageEvents
,
22 } from
'../types/ChargingStationWorker';
23 import type { StationTemplateUrl
} from
'../types/ConfigurationData';
24 import type { Statistics
} from
'../types/Statistics';
25 import type { MessageHandler
} from
'../types/Worker';
26 import Configuration from
'../utils/Configuration';
27 import logger from
'../utils/Logger';
28 import Utils from
'../utils/Utils';
29 import type WorkerAbstract from
'../worker/WorkerAbstract';
30 import WorkerFactory from
'../worker/WorkerFactory';
32 const moduleName
= 'Bootstrap';
35 missingChargingStationsConfiguration
= 1,
36 noChargingStationTemplates
= 2,
39 export class Bootstrap
{
40 private static instance
: Bootstrap
| null = null;
41 public numberOfChargingStations
!: number;
42 public numberOfChargingStationTemplates
!: number;
43 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
44 private readonly uiServer
!: AbstractUIServer
| null;
45 private readonly storage
!: Storage
;
46 private numberOfStartedChargingStations
!: number;
47 private readonly version
: string = version
;
48 private initializedCounters
: boolean;
49 private started
: boolean;
50 private readonly workerScript
: string;
52 private constructor() {
53 // Enable unconditionally for now
54 this.logUnhandledRejection();
55 this.logUncaughtException();
56 this.initializedCounters
= false;
58 this.initializeCounters();
59 this.workerImplementation
= null;
60 this.workerScript
= path
.join(
61 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
63 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
65 Configuration
.getUIServer().enabled
=== true &&
66 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
67 Configuration
.getPerformanceStorage().enabled
=== true &&
68 (this.storage
= StorageFactory
.getStorage(
69 Configuration
.getPerformanceStorage().type,
70 Configuration
.getPerformanceStorage().uri
,
73 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
76 public static getInstance(): Bootstrap
{
77 if (Bootstrap
.instance
=== null) {
78 Bootstrap
.instance
= new Bootstrap();
80 return Bootstrap
.instance
;
83 public async start(): Promise
<void> {
84 if (isMainThread
&& this.started
=== false) {
86 this.initializeCounters();
87 this.initializeWorkerImplementation();
88 await this.workerImplementation
?.start();
89 await this.storage
?.open();
90 this.uiServer
?.start();
91 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
92 // Start ChargingStation object instance in worker thread
93 for (const stationTemplateUrl
of stationTemplateUrls
) {
95 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
96 for (let index
= 1; index
<= nbStations
; index
++) {
97 await this.startChargingStation(index
, stationTemplateUrl
);
102 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
110 `Charging stations simulator ${
112 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
113 ChargingStationUtils.workerDynamicPoolInUse()
114 ? `${Configuration.getWorker().poolMinSize?.toString()}
/`
116 }${this.workerImplementation?.size}${
117 ChargingStationUtils.workerPoolInUse()
118 ? `/${Configuration.getWorker().poolMaxSize?.toString()}
`
120 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
121 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
122 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
129 console
.error(chalk
.red('Bootstrap start error: '), error
);
132 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
136 public async stop(): Promise
<void> {
137 if (isMainThread
&& this.started
=== true) {
138 this.initializedCounters
= false;
139 await this.workerImplementation
?.stop();
140 this.workerImplementation
= null;
141 this.uiServer
?.stop();
142 await this.storage
?.close();
143 this.started
= false;
145 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
149 public async restart(): Promise
<void> {
154 private initializeWorkerImplementation(): void {
155 this.workerImplementation
=== null &&
156 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
158 Configuration
.getWorker().processType
,
160 workerStartDelay
: Configuration
.getWorker().startDelay
,
161 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
162 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
163 poolMinSize
: Configuration
.getWorker().poolMinSize
,
164 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
166 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
168 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
173 private messageHandler(
174 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
177 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
185 case ChargingStationWorkerMessageEvents
.STARTED
:
186 this.workerEventStarted(msg
.data
as ChargingStationData
);
188 case ChargingStationWorkerMessageEvents
.STOPPED
:
189 this.workerEventStopped(msg
.data
as ChargingStationData
);
191 case ChargingStationWorkerMessageEvents
.UPDATED
:
192 this.workerEventUpdated(msg
.data
as ChargingStationData
);
194 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
195 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
199 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
204 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
212 private workerEventStarted
= (data
: ChargingStationData
) => {
213 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
214 ++this.numberOfStartedChargingStations
;
216 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
217 data.stationInfo.chargingStationId
218 } (hashId: ${data.stationInfo.hashId}) started (${
219 this.numberOfStartedChargingStations
220 } started from ${this.numberOfChargingStations})`
224 private workerEventStopped
= (data
: ChargingStationData
) => {
225 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
226 --this.numberOfStartedChargingStations
;
228 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
229 data.stationInfo.chargingStationId
230 } (hashId: ${data.stationInfo.hashId}) stopped (${
231 this.numberOfStartedChargingStations
232 } started from ${this.numberOfChargingStations})`
236 private workerEventUpdated
= (data
: ChargingStationData
) => {
237 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
240 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
241 this.storage
.storePerformanceStatistics(data
) as void;
244 private initializeCounters() {
245 if (this.initializedCounters
=== false) {
246 this.numberOfChargingStationTemplates
= 0;
247 this.numberOfChargingStations
= 0;
248 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
249 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
250 this.numberOfChargingStationTemplates
= stationTemplateUrls
?.length
;
251 stationTemplateUrls
.forEach((stationTemplateUrl
) => {
252 this.numberOfChargingStations
+= stationTemplateUrl
.numberOfStations
?? 0;
256 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
258 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
260 if (this.numberOfChargingStations
=== 0) {
262 chalk
.yellow('No charging station template enabled in configuration, exiting')
264 process
.exit(exitCodes
.noChargingStationTemplates
);
266 this.numberOfStartedChargingStations
= 0;
267 this.initializedCounters
= true;
271 private logUncaughtException(): void {
272 process
.on('uncaughtException', (error
: Error) => {
273 console
.error(chalk
.red('Uncaught exception: '), error
);
277 private logUnhandledRejection(): void {
278 process
.on('unhandledRejection', (reason
: unknown
) => {
279 console
.error(chalk
.red('Unhandled rejection: '), reason
);
283 private async startChargingStation(
285 stationTemplateUrl
: StationTemplateUrl
287 const workerData
: ChargingStationWorkerData
= {
289 templateFile
: path
.join(
290 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
293 stationTemplateUrl
.file
296 await this.workerImplementation
?.addElement(workerData
);
299 private logPrefix
= (): string => {
300 return Utils
.logPrefix(' Bootstrap |');