1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { EventEmitter
} from
'node:events';
4 import { dirname
, extname
, join
} from
'node:path';
5 import process
, { exit
} from
'node:process';
6 import { fileURLToPath
} from
'node:url';
8 import chalk from
'chalk';
9 import { availableParallelism
} from
'poolifier';
11 import { waitChargingStationEvents
} from
'./Helpers';
12 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
13 import { UIServerFactory
} from
'./ui-server/UIServerFactory';
14 import { version
} from
'../../package.json';
15 import { BaseError
} from
'../exception';
16 import { type Storage
, StorageFactory
} from
'../performance';
18 type ChargingStationData
,
19 type ChargingStationWorkerData
,
20 type ChargingStationWorkerMessage
,
21 type ChargingStationWorkerMessageData
,
22 ChargingStationWorkerMessageEvents
,
25 type StationTemplateUrl
,
27 type StorageConfiguration
,
28 type UIServerConfiguration
,
29 type WorkerConfiguration
,
34 formatDurationMilliSeconds
,
36 handleUncaughtException
,
37 handleUnhandledRejection
,
43 import { type WorkerAbstract
, WorkerFactory
} from
'../worker';
45 const moduleName
= 'Bootstrap';
49 missingChargingStationsConfiguration
= 1,
50 noChargingStationTemplates
= 2,
51 gracefulShutdownError
= 3,
54 export class Bootstrap
extends EventEmitter
{
55 private static instance
: Bootstrap
| null = null;
56 public numberOfChargingStations
!: number;
57 public numberOfChargingStationTemplates
!: number;
58 private workerImplementation
?: WorkerAbstract
<ChargingStationWorkerData
>;
59 private readonly uiServer
?: AbstractUIServer
;
60 private storage
?: Storage
;
61 private numberOfStartedChargingStations
!: number;
62 private readonly version
: string = version
;
63 private initializedCounters
: boolean;
64 private started
: boolean;
65 private starting
: boolean;
66 private stopping
: boolean;
68 private constructor() {
70 for (const signal
of ['SIGINT', 'SIGQUIT', 'SIGTERM']) {
71 process
.on(signal
, this.gracefulShutdown
.bind(this));
73 // Enable unconditionally for now
74 handleUnhandledRejection();
75 handleUncaughtException();
77 this.starting
= false;
78 this.stopping
= false;
79 this.initializedCounters
= false;
80 this.initializeCounters();
81 this.uiServer
= UIServerFactory
.getUIServerImplementation(
82 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
),
84 Configuration
.configurationChangeCallback
= async () => Bootstrap
.getInstance().restart(false);
87 public static getInstance(): Bootstrap
{
88 if (Bootstrap
.instance
=== null) {
89 Bootstrap
.instance
= new Bootstrap();
91 return Bootstrap
.instance
;
94 public async start(): Promise
<void> {
95 if (this.started
=== false) {
96 if (this.starting
=== false) {
98 this.on(ChargingStationWorkerMessageEvents
.started
, this.workerEventStarted
);
99 this.on(ChargingStationWorkerMessageEvents
.stopped
, this.workerEventStopped
);
100 this.on(ChargingStationWorkerMessageEvents
.updated
, this.workerEventUpdated
);
102 ChargingStationWorkerMessageEvents
.performanceStatistics
,
103 this.workerEventPerformanceStatistics
,
105 this.initializeCounters();
106 const workerConfiguration
= Configuration
.getConfigurationSection
<WorkerConfiguration
>(
107 ConfigurationSection
.worker
,
109 this.initializeWorkerImplementation(workerConfiguration
);
110 await this.workerImplementation
?.start();
111 const performanceStorageConfiguration
=
112 Configuration
.getConfigurationSection
<StorageConfiguration
>(
113 ConfigurationSection
.performanceStorage
,
115 if (performanceStorageConfiguration
.enabled
=== true) {
116 this.storage
= StorageFactory
.getStorage(
117 performanceStorageConfiguration
.type!,
118 performanceStorageConfiguration
.uri
!,
121 await this.storage
?.open();
123 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
)
124 .enabled
=== true && this.uiServer
?.start();
125 // Start ChargingStation object instance in worker thread
126 for (const stationTemplateUrl
of Configuration
.getStationTemplateUrls()!) {
128 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
129 for (let index
= 1; index
<= nbStations
; index
++) {
130 await this.startChargingStation(index
, stationTemplateUrl
);
135 `Error at starting charging station with template file ${stationTemplateUrl.file}: `,
143 `Charging stations simulator ${
145 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
146 Configuration.workerDynamicPoolInUse()
147 ? `${workerConfiguration.poolMinSize?.toString()}
/`
149 }${this.workerImplementation?.size}${
150 Configuration.workerPoolInUse()
151 ? `/${workerConfiguration.poolMaxSize?.toString()}
`
153 } worker(s) concurrently running in '${workerConfiguration.processType}' mode${
154 !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
155 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
160 Configuration
.workerDynamicPoolInUse() &&
163 'Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using fixed pool or worker set mode instead',
166 console
.info(chalk
.green('Worker set/pool information:'), this.workerImplementation
?.info
);
168 this.starting
= false;
170 console
.error(chalk
.red('Cannot start an already starting charging stations simulator'));
173 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
177 public async stop(stopChargingStations
= true): Promise
<void> {
178 if (this.started
=== true) {
179 if (this.stopping
=== false) {
180 this.stopping
= true;
181 if (stopChargingStations
=== true) {
182 await this.uiServer
?.sendInternalRequest(
183 this.uiServer
.buildProtocolRequest(
185 ProcedureName
.STOP_CHARGING_STATION
,
186 Constants
.EMPTY_FROZEN_OBJECT
,
190 await this.waitChargingStationsStopped();
192 console
.error(chalk
.red('Error while waiting for charging stations to stop: '), error
);
195 await this.workerImplementation
?.stop();
196 delete this.workerImplementation
;
197 this.removeAllListeners();
198 this.uiServer
?.stop();
199 await this.storage
?.close();
201 this.resetCounters();
202 this.initializedCounters
= false;
203 this.started
= false;
204 this.stopping
= false;
206 console
.error(chalk
.red('Cannot stop an already stopping charging stations simulator'));
209 console
.error(chalk
.red('Cannot stop an already stopped charging stations simulator'));
213 public async restart(stopChargingStations
?: boolean): Promise
<void> {
214 await this.stop(stopChargingStations
);
218 private async waitChargingStationsStopped(): Promise
<string> {
219 return new Promise
<string>((resolve
, reject
) => {
220 const waitTimeout
= setTimeout(() => {
221 const message
= `Timeout ${formatDurationMilliSeconds(
222 Constants.STOP_CHARGING_STATIONS_TIMEOUT,
223 )} reached at stopping charging stations`;
224 console
.warn(chalk
.yellow(message
));
225 reject(new Error(message
));
226 }, Constants
.STOP_CHARGING_STATIONS_TIMEOUT
);
227 waitChargingStationEvents(
229 ChargingStationWorkerMessageEvents
.stopped
,
230 this.numberOfChargingStations
,
233 resolve('Charging stations stopped');
237 clearTimeout(waitTimeout
);
242 private initializeWorkerImplementation(workerConfiguration
: WorkerConfiguration
): void {
243 let elementsPerWorker
: number | undefined;
244 switch (workerConfiguration
?.elementsPerWorker
) {
247 this.numberOfChargingStations
> availableParallelism()
248 ? Math.round(this.numberOfChargingStations
/ (availableParallelism() * 1.5))
252 elementsPerWorker
= this.numberOfChargingStations
;
255 this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
257 dirname(fileURLToPath(import.meta
.url
)),
258 `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`,
260 workerConfiguration
.processType
!,
262 workerStartDelay
: workerConfiguration
.startDelay
,
263 elementStartDelay
: workerConfiguration
.elementStartDelay
,
264 poolMaxSize
: workerConfiguration
.poolMaxSize
!,
265 poolMinSize
: workerConfiguration
.poolMinSize
!,
266 elementsPerWorker
: elementsPerWorker
?? (workerConfiguration
.elementsPerWorker
as number),
268 messageHandler
: this.messageHandler
.bind(this) as (message
: unknown
) => void,
269 workerOptions
: { resourceLimits
: workerConfiguration
.resourceLimits
},
275 private messageHandler(
276 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>,
279 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
287 case ChargingStationWorkerMessageEvents
.started
:
288 this.emit(ChargingStationWorkerMessageEvents
.started
, msg
.data
as ChargingStationData
);
290 case ChargingStationWorkerMessageEvents
.stopped
:
291 this.emit(ChargingStationWorkerMessageEvents
.stopped
, msg
.data
as ChargingStationData
);
293 case ChargingStationWorkerMessageEvents
.updated
:
294 this.emit(ChargingStationWorkerMessageEvents
.updated
, msg
.data
as ChargingStationData
);
296 case ChargingStationWorkerMessageEvents
.performanceStatistics
:
298 ChargingStationWorkerMessageEvents
.performanceStatistics
,
299 msg
.data
as Statistics
,
302 case ChargingStationWorkerMessageEvents
.startWorkerElementError
:
304 `${this.logPrefix()} ${moduleName}.messageHandler: Error occured while starting worker element:`,
307 this.emit(ChargingStationWorkerMessageEvents
.startWorkerElementError
, msg
.data
);
309 case ChargingStationWorkerMessageEvents
.startedWorkerElement
:
313 `Unknown charging station worker event: '${
315 }' received with data: ${JSON.stringify(msg.data, undefined, 2)}`,
320 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
328 private workerEventStarted
= (data
: ChargingStationData
) => {
329 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
330 ++this.numberOfStartedChargingStations
;
332 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
333 data.stationInfo.chargingStationId
334 } (hashId: ${data.stationInfo.hashId}) started (${
335 this.numberOfStartedChargingStations
336 } started from ${this.numberOfChargingStations})`,
340 private workerEventStopped
= (data
: ChargingStationData
) => {
341 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
342 --this.numberOfStartedChargingStations
;
344 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
345 data.stationInfo.chargingStationId
346 } (hashId: ${data.stationInfo.hashId}) stopped (${
347 this.numberOfStartedChargingStations
348 } started from ${this.numberOfChargingStations})`,
352 private workerEventUpdated
= (data
: ChargingStationData
) => {
353 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
356 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
357 this.storage
?.storePerformanceStatistics(data
) as void;
360 private initializeCounters() {
361 if (this.initializedCounters
=== false) {
362 this.resetCounters();
363 const stationTemplateUrls
= Configuration
.getStationTemplateUrls()!;
364 if (isNotEmptyArray(stationTemplateUrls
)) {
365 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
366 for (const stationTemplateUrl
of stationTemplateUrls
) {
367 this.numberOfChargingStations
+= stationTemplateUrl
.numberOfStations
?? 0;
371 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting"),
373 exit(exitCodes
.missingChargingStationsConfiguration
);
375 if (this.numberOfChargingStations
=== 0) {
377 chalk
.yellow('No charging station template enabled in configuration, exiting'),
379 exit(exitCodes
.noChargingStationTemplates
);
381 this.initializedCounters
= true;
385 private resetCounters(): void {
386 this.numberOfChargingStationTemplates
= 0;
387 this.numberOfChargingStations
= 0;
388 this.numberOfStartedChargingStations
= 0;
391 private async startChargingStation(
393 stationTemplateUrl
: StationTemplateUrl
,
395 await this.workerImplementation
?.addElement({
398 dirname(fileURLToPath(import.meta
.url
)),
401 stationTemplateUrl
.file
,
406 private gracefulShutdown(): void {
409 console
.info(`${chalk.green('Graceful shutdown')}`);
410 // stop() asks for charging stations to stop by default
411 this.waitChargingStationsStopped()
413 exit(exitCodes
.succeeded
);
416 exit(exitCodes
.gracefulShutdownError
);
420 console
.error(chalk
.red('Error while shutdowning charging stations simulator: '), error
);
421 exit(exitCodes
.gracefulShutdownError
);
425 private logPrefix
= (): string => {
426 return logPrefix(' Bootstrap |');