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';
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 type StationTemplateUrl
,
25 import { Configuration
} from
'../utils/Configuration';
26 import { logger
} from
'../utils/Logger';
27 import { Utils
} from
'../utils/Utils';
28 import { type MessageHandler
, type WorkerAbstract
, WorkerFactory
} from
'../worker';
30 const moduleName
= 'Bootstrap';
33 missingChargingStationsConfiguration
= 1,
34 noChargingStationTemplates
= 2,
37 export class Bootstrap
{
38 private static instance
: Bootstrap
| null = null;
39 public numberOfChargingStations
!: number;
40 public numberOfChargingStationTemplates
!: number;
41 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
42 private readonly uiServer
!: AbstractUIServer
| null;
43 private readonly storage
!: Storage
;
44 private numberOfStartedChargingStations
!: number;
45 private readonly version
: string = version
;
46 private initializedCounters
: boolean;
47 private started
: boolean;
48 private readonly workerScript
: string;
50 private constructor() {
51 // Enable unconditionally for now
52 this.logUnhandledRejection();
53 this.logUncaughtException();
54 this.initializedCounters
= false;
56 this.initializeCounters();
57 this.workerImplementation
= null;
58 this.workerScript
= path
.join(
59 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
61 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
63 Configuration
.getUIServer().enabled
=== true &&
64 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
65 Configuration
.getPerformanceStorage().enabled
=== true &&
66 (this.storage
= StorageFactory
.getStorage(
67 Configuration
.getPerformanceStorage().type,
68 Configuration
.getPerformanceStorage().uri
,
71 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
74 public static getInstance(): Bootstrap
{
75 if (Bootstrap
.instance
=== null) {
76 Bootstrap
.instance
= new Bootstrap();
78 return Bootstrap
.instance
;
81 public async start(): Promise
<void> {
82 if (isMainThread
&& this.started
=== false) {
83 this.initializeCounters();
84 this.initializeWorkerImplementation();
85 await this.workerImplementation
?.start();
86 await this.storage
?.open();
87 this.uiServer
?.start();
88 // Start ChargingStation object instance in worker thread
89 for (const stationTemplateUrl
of Configuration
.getStationTemplateUrls()) {
91 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
92 for (let index
= 1; index
<= nbStations
; index
++) {
93 await this.startChargingStation(index
, stationTemplateUrl
);
98 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
106 `Charging stations simulator ${
108 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
109 ChargingStationUtils.workerDynamicPoolInUse()
110 ? `${Configuration.getWorker().poolMinSize?.toString()}
/`
112 }${this.workerImplementation?.size}${
113 ChargingStationUtils.workerPoolInUse()
114 ? `/${Configuration.getWorker().poolMaxSize?.toString()}
`
116 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
117 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
118 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
125 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
129 public async stop(): Promise
<void> {
130 if (isMainThread
&& this.started
=== true) {
131 await this.workerImplementation
?.stop();
132 this.workerImplementation
= null;
133 this.uiServer
?.stop();
134 await this.storage
?.close();
135 this.initializedCounters
= false;
136 this.started
= false;
138 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
142 public async restart(): Promise
<void> {
147 private initializeWorkerImplementation(): void {
148 this.workerImplementation
=== null &&
149 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
151 Configuration
.getWorker().processType
,
153 workerStartDelay
: Configuration
.getWorker().startDelay
,
154 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
155 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
156 poolMinSize
: Configuration
.getWorker().poolMinSize
,
157 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
159 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
161 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
166 private messageHandler(
167 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
170 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
178 case ChargingStationWorkerMessageEvents
.STARTED
:
179 this.workerEventStarted(msg
.data
as ChargingStationData
);
181 case ChargingStationWorkerMessageEvents
.STOPPED
:
182 this.workerEventStopped(msg
.data
as ChargingStationData
);
184 case ChargingStationWorkerMessageEvents
.UPDATED
:
185 this.workerEventUpdated(msg
.data
as ChargingStationData
);
187 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
188 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
192 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
197 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
205 private workerEventStarted
= (data
: ChargingStationData
) => {
206 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
207 ++this.numberOfStartedChargingStations
;
209 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
210 data.stationInfo.chargingStationId
211 } (hashId: ${data.stationInfo.hashId}) started (${
212 this.numberOfStartedChargingStations
213 } started from ${this.numberOfChargingStations})`
217 private workerEventStopped
= (data
: ChargingStationData
) => {
218 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
219 --this.numberOfStartedChargingStations
;
221 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
222 data.stationInfo.chargingStationId
223 } (hashId: ${data.stationInfo.hashId}) stopped (${
224 this.numberOfStartedChargingStations
225 } started from ${this.numberOfChargingStations})`
229 private workerEventUpdated
= (data
: ChargingStationData
) => {
230 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
233 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
234 this.storage
.storePerformanceStatistics(data
) as void;
237 private initializeCounters() {
238 if (this.initializedCounters
=== false) {
239 this.numberOfChargingStationTemplates
= 0;
240 this.numberOfChargingStations
= 0;
241 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
242 if (Utils
.isNotEmptyArray(stationTemplateUrls
)) {
243 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
244 stationTemplateUrls
.forEach((stationTemplateUrl
) => {
245 this.numberOfChargingStations
+= stationTemplateUrl
.numberOfStations
?? 0;
249 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
251 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
253 if (this.numberOfChargingStations
=== 0) {
255 chalk
.yellow('No charging station template enabled in configuration, exiting')
257 process
.exit(exitCodes
.noChargingStationTemplates
);
259 this.numberOfStartedChargingStations
= 0;
260 this.initializedCounters
= true;
264 private logUncaughtException(): void {
265 process
.on('uncaughtException', (error
: Error) => {
266 console
.error(chalk
.red('Uncaught exception: '), error
);
270 private logUnhandledRejection(): void {
271 process
.on('unhandledRejection', (reason
: unknown
) => {
272 console
.error(chalk
.red('Unhandled rejection: '), reason
);
276 private async startChargingStation(
278 stationTemplateUrl
: StationTemplateUrl
280 await this.workerImplementation
?.addElement({
282 templateFile
: path
.join(
283 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
286 stationTemplateUrl
.file
291 private logPrefix
= (): string => {
292 return Utils
.logPrefix(' Bootstrap |');