1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import path from
'path';
4 import { fileURLToPath
} from
'url';
5 import { type Worker
, isMainThread
} from
'worker_threads';
7 import chalk from
'chalk';
9 import { version
} from
'../../package.json';
10 import BaseError from
'../exception/BaseError';
11 import type { Storage
} from
'../performance/storage/Storage';
12 import { StorageFactory
} from
'../performance/storage/StorageFactory';
14 type ChargingStationData
,
15 type ChargingStationWorkerData
,
16 type ChargingStationWorkerMessage
,
17 type ChargingStationWorkerMessageData
,
18 ChargingStationWorkerMessageEvents
,
19 } from
'../types/ChargingStationWorker';
20 import type { StationTemplateUrl
} from
'../types/ConfigurationData';
21 import type { Statistics
} from
'../types/Statistics';
22 import type { MessageHandler
} from
'../types/Worker';
23 import Configuration from
'../utils/Configuration';
24 import logger from
'../utils/Logger';
25 import Utils from
'../utils/Utils';
26 import type WorkerAbstract from
'../worker/WorkerAbstract';
27 import WorkerFactory from
'../worker/WorkerFactory';
28 import { ChargingStationUtils
} from
'./ChargingStationUtils';
29 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
30 import UIServerFactory from
'./ui-server/UIServerFactory';
32 const moduleName
= 'Bootstrap';
35 missingChargingStationsConfiguration
= 1,
36 noChargingStationTemplates
= 2,
39 export class Bootstrap
{
40 private static instance
: Bootstrap
| null = null;
41 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
42 private readonly uiServer
!: AbstractUIServer
;
43 private readonly storage
!: Storage
;
44 private numberOfChargingStationTemplates
!: number;
45 private numberOfChargingStations
!: number;
46 private numberOfStartedChargingStations
!: number;
47 private readonly version
: string = version
;
48 private started
: boolean;
49 private readonly workerScript
: string;
51 private constructor() {
53 this.workerImplementation
= null;
54 this.workerScript
= path
.join(
55 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
57 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
60 Configuration
.getUIServer().enabled
=== true &&
61 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
62 Configuration
.getPerformanceStorage().enabled
=== true &&
63 (this.storage
= StorageFactory
.getStorage(
64 Configuration
.getPerformanceStorage().type,
65 Configuration
.getPerformanceStorage().uri
,
68 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
71 public static getInstance(): Bootstrap
{
72 if (Bootstrap
.instance
=== null) {
73 Bootstrap
.instance
= new Bootstrap();
75 return Bootstrap
.instance
;
78 public async start(): Promise
<void> {
79 if (isMainThread
&& this.started
=== false) {
81 // Enable unconditionally for now
82 this.logUnhandledRejection();
83 this.logUncaughtException();
85 await this.storage
?.open();
86 await this.workerImplementation
.start();
87 this.uiServer
?.start();
88 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
89 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
90 // Start ChargingStation object in worker thread
91 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
92 for (const stationTemplateUrl
of stationTemplateUrls
) {
94 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
95 for (let index
= 1; index
<= nbStations
; index
++) {
96 await this.startChargingStation(index
, stationTemplateUrl
);
101 'Error at starting charging station with template file ' +
102 stationTemplateUrl
.file
+
111 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
113 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
115 if (this.numberOfChargingStations
=== 0) {
117 chalk
.yellow('No charging station template enabled in configuration, exiting')
119 process
.exit(exitCodes
.noChargingStationTemplates
);
123 `Charging stations simulator ${
125 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
126 ChargingStationUtils.workerDynamicPoolInUse()
127 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
129 }${this.workerImplementation.size}${
130 ChargingStationUtils.workerPoolInUse()
131 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
133 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
134 this.workerImplementation.maxElementsPerWorker
135 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
143 console
.error(chalk
.red('Bootstrap start error: '), error
);
146 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
150 public async stop(): Promise
<void> {
151 if (isMainThread
&& this.started
=== true) {
152 await this.workerImplementation
.stop();
153 this.workerImplementation
= null;
154 this.uiServer
?.stop();
155 await this.storage
?.close();
156 this.started
= false;
158 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
162 public async restart(): Promise
<void> {
168 private initializeWorkerImplementation(): void {
169 this.workerImplementation
=== null &&
170 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
172 Configuration
.getWorker().processType
,
174 workerStartDelay
: Configuration
.getWorker().startDelay
,
175 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
176 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
177 poolMinSize
: Configuration
.getWorker().poolMinSize
,
178 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
180 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
182 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
187 private messageHandler(
188 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
191 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
199 case ChargingStationWorkerMessageEvents
.STARTED
:
200 this.workerEventStarted(msg
.data
as ChargingStationData
);
202 case ChargingStationWorkerMessageEvents
.STOPPED
:
203 this.workerEventStopped(msg
.data
as ChargingStationData
);
205 case ChargingStationWorkerMessageEvents
.UPDATED
:
206 this.workerEventUpdated(msg
.data
as ChargingStationData
);
208 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
209 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
213 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
218 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
226 private workerEventStarted
= (data
: ChargingStationData
) => {
227 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
228 ++this.numberOfStartedChargingStations
;
230 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
231 data.stationInfo.chargingStationId
232 } (hashId: ${data.stationInfo.hashId}) started (${
233 this.numberOfStartedChargingStations
234 } started from ${this.numberOfChargingStations})`
238 private workerEventStopped
= (data
: ChargingStationData
) => {
239 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
240 --this.numberOfStartedChargingStations
;
242 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
243 data.stationInfo.chargingStationId
244 } (hashId: ${data.stationInfo.hashId}) stopped (${
245 this.numberOfStartedChargingStations
246 } started from ${this.numberOfChargingStations})`
250 private workerEventUpdated
= (data
: ChargingStationData
) => {
251 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
254 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
255 this.storage
.storePerformanceStatistics(data
) as void;
258 private initialize() {
259 this.numberOfChargingStationTemplates
= 0;
260 this.numberOfChargingStations
= 0;
261 this.numberOfStartedChargingStations
= 0;
262 this.initializeWorkerImplementation();
265 private logUncaughtException(): void {
266 process
.on('uncaughtException', (error
: Error) => {
267 console
.error(chalk
.red('Uncaught exception: '), error
);
271 private logUnhandledRejection(): void {
272 process
.on('unhandledRejection', (reason
: unknown
) => {
273 console
.error(chalk
.red('Unhandled rejection: '), reason
);
277 private async startChargingStation(
279 stationTemplateUrl
: StationTemplateUrl
281 const workerData
: ChargingStationWorkerData
= {
283 templateFile
: path
.join(
284 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
287 stationTemplateUrl
.file
290 await this.workerImplementation
.addElement(workerData
);
291 ++this.numberOfChargingStations
;
294 private logPrefix(): string {
295 return Utils
.logPrefix(' Bootstrap |');