1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { EventEmitter
} from
'node:events';
4 import path from
'node:path';
5 import { fileURLToPath
} from
'node:url';
6 import { isMainThread
} from
'node:worker_threads';
8 import chalk from
'chalk';
10 import { ChargingStationUtils
} from
'./ChargingStationUtils';
11 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
12 import { UIServerFactory
} from
'./ui-server/UIServerFactory';
13 import packageJson from
'../../package.json' assert
{ type: 'json' };
14 import { BaseError
} from
'../exception';
15 import { type Storage
, StorageFactory
} from
'../performance';
17 type ChargingStationData
,
18 type ChargingStationWorkerData
,
19 type ChargingStationWorkerMessage
,
20 type ChargingStationWorkerMessageData
,
21 ChargingStationWorkerMessageEvents
,
23 type StationTemplateUrl
,
30 handleUncaughtException
,
31 handleUnhandledRejection
,
34 import { type WorkerAbstract
, WorkerFactory
} from
'../worker';
36 const moduleName
= 'Bootstrap';
39 missingChargingStationsConfiguration
= 1,
40 noChargingStationTemplates
= 2,
43 export class Bootstrap
extends EventEmitter
{
44 private static instance
: Bootstrap
| null = null;
45 public numberOfChargingStations
!: number;
46 public numberOfChargingStationTemplates
!: number;
47 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
48 private readonly uiServer
!: AbstractUIServer
| null;
49 private readonly storage
!: Storage
;
50 private numberOfStartedChargingStations
!: number;
51 private readonly version
: string = packageJson
.version
;
52 private initializedCounters
: boolean;
53 private started
: boolean;
54 private starting
: boolean;
55 private stopping
: boolean;
56 private readonly workerScript
: string;
58 private constructor() {
60 for (const signal
of ['SIGINT', 'SIGQUIT', 'SIGTERM']) {
61 process
.on(signal
, this.gracefulShutdown
);
63 // Enable unconditionally for now
64 handleUnhandledRejection();
65 handleUncaughtException();
67 this.starting
= false;
68 this.stopping
= false;
69 this.initializedCounters
= false;
70 this.initializeCounters();
71 this.workerImplementation
= null;
72 this.workerScript
= path
.join(
73 path
.dirname(fileURLToPath(import.meta
.url
)),
74 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
76 Configuration
.getUIServer().enabled
=== true &&
77 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
78 Configuration
.getPerformanceStorage().enabled
=== true &&
79 (this.storage
= StorageFactory
.getStorage(
80 Configuration
.getPerformanceStorage().type,
81 Configuration
.getPerformanceStorage().uri
,
84 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
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> {
96 throw new Error('Cannot start charging stations simulator from worker thread');
98 if (this.started
=== false) {
99 if (this.starting
=== false) {
100 this.starting
= true;
101 this.initializeCounters();
102 this.initializeWorkerImplementation();
103 await this.workerImplementation
?.start();
104 await this.storage
?.open();
105 this.uiServer
?.start();
106 // Start ChargingStation object instance in worker thread
107 for (const stationTemplateUrl
of Configuration
.getStationTemplateUrls()) {
109 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
110 for (let index
= 1; index
<= nbStations
; index
++) {
111 await this.startChargingStation(index
, stationTemplateUrl
);
116 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
124 `Charging stations simulator ${
126 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
127 Configuration.workerDynamicPoolInUse()
128 ? `${Configuration.getWorker().poolMinSize?.toString()}
/`
130 }${this.workerImplementation?.size}${
131 Configuration.workerPoolInUse()
132 ? `/${Configuration.getWorker().poolMaxSize?.toString()}
`
134 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
135 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
136 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
142 this.starting
= false;
144 console
.error(chalk
.red('Cannot start an already starting charging stations simulator'));
147 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
151 public async stop(): Promise
<void> {
153 throw new Error('Cannot stop charging stations simulator from worker thread');
155 if (this.started
=== true) {
156 if (this.stopping
=== false) {
157 this.stopping
= true;
158 await this.uiServer
?.sendInternalRequest(
159 this.uiServer
.buildProtocolRequest(
160 Utils
.generateUUID(),
161 ProcedureName
.STOP_CHARGING_STATION
,
162 Constants
.EMPTY_FREEZED_OBJECT
166 ChargingStationUtils
.waitForChargingStationEvents(
168 ChargingStationWorkerMessageEvents
.stopped
,
169 this.numberOfChargingStations
171 new Promise
<string>((resolve
) => {
173 const message
= `Timeout reached ${Utils.formatDurationMilliSeconds(
174 Constants.STOP_SIMULATOR_TIMEOUT
175 )} at stopping charging stations simulator`;
176 console
.warn(chalk
.yellow(message
));
178 }, Constants
.STOP_SIMULATOR_TIMEOUT
);
181 await this.workerImplementation
?.stop();
182 this.workerImplementation
= null;
183 this.uiServer
?.stop();
184 await this.storage
?.close();
185 this.resetCounters();
186 this.initializedCounters
= false;
187 this.started
= false;
188 this.stopping
= false;
190 console
.error(chalk
.red('Cannot stop an already stopping charging stations simulator'));
193 console
.error(chalk
.red('Cannot stop an already stopped charging stations simulator'));
197 public async restart(): Promise
<void> {
202 private initializeWorkerImplementation(): void {
203 this.workerImplementation
=== null &&
204 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
206 Configuration
.getWorker().processType
,
208 workerStartDelay
: Configuration
.getWorker().startDelay
,
209 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
210 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
211 poolMinSize
: Configuration
.getWorker().poolMinSize
,
212 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
214 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
215 messageHandler
: this.messageHandler
.bind(this) as (message
: unknown
) => void,
221 private messageHandler(
222 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
225 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
233 case ChargingStationWorkerMessageEvents
.started
:
234 this.workerEventStarted(msg
.data
as ChargingStationData
);
235 this.emit(ChargingStationWorkerMessageEvents
.started
, msg
.data
as ChargingStationData
);
237 case ChargingStationWorkerMessageEvents
.stopped
:
238 this.workerEventStopped(msg
.data
as ChargingStationData
);
239 this.emit(ChargingStationWorkerMessageEvents
.stopped
, msg
.data
as ChargingStationData
);
241 case ChargingStationWorkerMessageEvents
.updated
:
242 this.workerEventUpdated(msg
.data
as ChargingStationData
);
243 this.emit(ChargingStationWorkerMessageEvents
.updated
, msg
.data
as ChargingStationData
);
245 case ChargingStationWorkerMessageEvents
.performanceStatistics
:
246 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
248 ChargingStationWorkerMessageEvents
.performanceStatistics
,
249 msg
.data
as Statistics
254 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
259 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
267 private workerEventStarted
= (data
: ChargingStationData
) => {
268 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
269 ++this.numberOfStartedChargingStations
;
271 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
272 data.stationInfo.chargingStationId
273 } (hashId: ${data.stationInfo.hashId}) started (${
274 this.numberOfStartedChargingStations
275 } started from ${this.numberOfChargingStations})`
279 private workerEventStopped
= (data
: ChargingStationData
) => {
280 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
281 --this.numberOfStartedChargingStations
;
283 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
284 data.stationInfo.chargingStationId
285 } (hashId: ${data.stationInfo.hashId}) stopped (${
286 this.numberOfStartedChargingStations
287 } started from ${this.numberOfChargingStations})`
291 private workerEventUpdated
= (data
: ChargingStationData
) => {
292 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
295 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
296 this.storage
.storePerformanceStatistics(data
) as void;
299 private initializeCounters() {
300 if (this.initializedCounters
=== false) {
301 this.resetCounters();
302 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
303 if (Utils
.isNotEmptyArray(stationTemplateUrls
)) {
304 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
305 for (const stationTemplateUrl
of stationTemplateUrls
) {
306 this.numberOfChargingStations
+= stationTemplateUrl
.numberOfStations
?? 0;
310 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
312 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
314 if (this.numberOfChargingStations
=== 0) {
316 chalk
.yellow('No charging station template enabled in configuration, exiting')
318 process
.exit(exitCodes
.noChargingStationTemplates
);
320 this.initializedCounters
= true;
324 private resetCounters(): void {
325 this.numberOfChargingStationTemplates
= 0;
326 this.numberOfChargingStations
= 0;
327 this.numberOfStartedChargingStations
= 0;
330 private async startChargingStation(
332 stationTemplateUrl
: StationTemplateUrl
334 await this.workerImplementation
?.addElement({
336 templateFile
: path
.join(
337 path
.dirname(fileURLToPath(import.meta
.url
)),
340 stationTemplateUrl
.file
345 private gracefulShutdown
= (): void => {
346 console
.info(`${chalk.green('Graceful shutdown')}`);
352 console
.error(chalk
.red('Error while shutdowning charging stations simulator: '), error
);
357 private logPrefix
= (): string => {
358 return Utils
.logPrefix(' Bootstrap |');