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 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 // Start ChargingStation object in worker thread
90 for (const stationTemplateUrl
of stationTemplateUrls
) {
92 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
93 for (let index
= 1; index
<= nbStations
; index
++) {
94 await this.startChargingStation(index
, stationTemplateUrl
);
99 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
107 `Charging stations simulator ${
109 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
110 ChargingStationUtils.workerDynamicPoolInUse()
111 ? `${Configuration.getWorker().poolMinSize?.toString()}
/`
113 }${this.workerImplementation?.size}${
114 ChargingStationUtils.workerPoolInUse()
115 ? `/${Configuration.getWorker().poolMaxSize?.toString()}
`
117 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
118 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
119 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
126 console
.error(chalk
.red('Bootstrap start error: '), error
);
129 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
133 public async stop(): Promise
<void> {
134 if (isMainThread
&& this.started
=== true) {
135 await this.workerImplementation
?.stop();
136 this.workerImplementation
= null;
137 this.uiServer
?.stop();
138 await this.storage
?.close();
139 this.started
= false;
141 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
145 public async restart(): Promise
<void> {
151 private initializeWorkerImplementation(): void {
152 this.workerImplementation
=== null &&
153 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
155 Configuration
.getWorker().processType
,
157 workerStartDelay
: Configuration
.getWorker().startDelay
,
158 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
159 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
160 poolMinSize
: Configuration
.getWorker().poolMinSize
,
161 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
163 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
165 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
170 private messageHandler(
171 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
174 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
182 case ChargingStationWorkerMessageEvents
.STARTED
:
183 this.workerEventStarted(msg
.data
as ChargingStationData
);
185 case ChargingStationWorkerMessageEvents
.STOPPED
:
186 this.workerEventStopped(msg
.data
as ChargingStationData
);
188 case ChargingStationWorkerMessageEvents
.UPDATED
:
189 this.workerEventUpdated(msg
.data
as ChargingStationData
);
191 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
192 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
196 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
201 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
209 private workerEventStarted
= (data
: ChargingStationData
) => {
210 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
211 ++this.numberOfStartedChargingStations
;
213 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
214 data.stationInfo.chargingStationId
215 } (hashId: ${data.stationInfo.hashId}) started (${
216 this.numberOfStartedChargingStations
217 } started from ${this.numberOfChargingStations})`
221 private workerEventStopped
= (data
: ChargingStationData
) => {
222 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
223 --this.numberOfStartedChargingStations
;
225 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
226 data.stationInfo.chargingStationId
227 } (hashId: ${data.stationInfo.hashId}) stopped (${
228 this.numberOfStartedChargingStations
229 } started from ${this.numberOfChargingStations})`
233 private workerEventUpdated
= (data
: ChargingStationData
) => {
234 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
237 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
238 this.storage
.storePerformanceStatistics(data
) as void;
241 private initialize() {
242 this.numberOfChargingStationTemplates
= 0;
243 this.numberOfChargingStations
= 0;
244 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
245 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
246 this.numberOfChargingStationTemplates
= stationTemplateUrls
?.length
;
247 stationTemplateUrls
.forEach((stationTemplateUrl
) => {
248 this.numberOfChargingStations
+= stationTemplateUrl
.numberOfStations
?? 0;
252 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
254 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
256 if (this.numberOfChargingStations
=== 0) {
257 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
258 process
.exit(exitCodes
.noChargingStationTemplates
);
260 this.numberOfStartedChargingStations
= 0;
261 this.initializeWorkerImplementation();
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 const workerData
: ChargingStationWorkerData
= {
282 templateFile
: path
.join(
283 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
286 stationTemplateUrl
.file
289 await this.workerImplementation
?.addElement(workerData
);
292 private logPrefix
= (): string => {
293 return Utils
.logPrefix(' Bootstrap |');