1 // Partial Copyright Jerome Benoit. 2021. 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';
15 ChargingStationWorkerData
,
16 ChargingStationWorkerMessage
,
17 ChargingStationWorkerMessageData
,
18 ChargingStationWorkerMessageEvents
,
19 } from
'../types/ChargingStationWorker';
20 import type { StationTemplateUrl
} from
'../types/ConfigurationData';
21 import type { Statistics
} from
'../types/Statistics';
22 import Configuration from
'../utils/Configuration';
23 import logger from
'../utils/Logger';
24 import Utils from
'../utils/Utils';
25 import type WorkerAbstract from
'../worker/WorkerAbstract';
26 import WorkerFactory from
'../worker/WorkerFactory';
27 import { ChargingStationUtils
} from
'./ChargingStationUtils';
28 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
29 import UIServerFactory from
'./ui-server/UIServerFactory';
31 const moduleName
= 'Bootstrap';
34 missingChargingStationsConfiguration
= 1,
35 noChargingStationTemplates
= 2,
38 export class Bootstrap
{
39 private static instance
: Bootstrap
| null = null;
40 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
41 private readonly uiServer
!: AbstractUIServer
;
42 private readonly storage
!: Storage
;
43 private numberOfChargingStationTemplates
!: number;
44 private numberOfChargingStations
!: number;
45 private numberOfStartedChargingStations
!: number;
46 private readonly version
: string = version
;
47 private started
: boolean;
48 private readonly workerScript
: string;
50 private constructor() {
52 this.workerImplementation
= null;
53 this.workerScript
= path
.join(
54 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
56 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
59 Configuration
.getUIServer().enabled
=== true &&
60 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
61 Configuration
.getPerformanceStorage().enabled
=== true &&
62 (this.storage
= StorageFactory
.getStorage(
63 Configuration
.getPerformanceStorage().type,
64 Configuration
.getPerformanceStorage().uri
,
67 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
70 public static getInstance(): Bootstrap
{
71 if (Bootstrap
.instance
=== null) {
72 Bootstrap
.instance
= new Bootstrap();
74 return Bootstrap
.instance
;
77 public async start(): Promise
<void> {
78 if (isMainThread
&& this.started
=== false) {
80 // Enable unconditionally for now
81 this.logUnhandledRejection();
82 this.logUncaughtException();
84 await this.storage
?.open();
85 await this.workerImplementation
.start();
86 this.uiServer
?.start();
87 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
88 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
89 // Start ChargingStation object in worker thread
90 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
91 for (const stationTemplateUrl
of stationTemplateUrls
) {
93 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
94 for (let index
= 1; index
<= nbStations
; index
++) {
95 await this.startChargingStation(index
, stationTemplateUrl
);
100 'Error at starting charging station with template file ' +
101 stationTemplateUrl
.file
+
110 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
112 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
114 if (this.numberOfChargingStations
=== 0) {
116 chalk
.yellow('No charging station template enabled in configuration, exiting')
118 process
.exit(exitCodes
.noChargingStationTemplates
);
122 `Charging stations simulator ${
124 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
125 ChargingStationUtils.workerDynamicPoolInUse()
126 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
128 }${this.workerImplementation.size}${
129 ChargingStationUtils.workerPoolInUse()
130 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
132 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
133 this.workerImplementation.maxElementsPerWorker
134 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
142 console
.error(chalk
.red('Bootstrap start error: '), error
);
145 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
149 public async stop(): Promise
<void> {
150 if (isMainThread
&& this.started
=== true) {
151 await this.workerImplementation
.stop();
152 this.workerImplementation
= null;
153 this.uiServer
?.stop();
154 await this.storage
?.close();
155 this.started
= false;
157 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
161 public async restart(): Promise
<void> {
167 private initializeWorkerImplementation(): void {
168 this.workerImplementation
=== null &&
169 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
171 Configuration
.getWorker().processType
,
173 workerStartDelay
: Configuration
.getWorker().startDelay
,
174 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
175 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
176 poolMinSize
: Configuration
.getWorker().poolMinSize
,
177 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
179 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
181 messageHandler
: this.messageHandler
.bind(this) as (
183 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
189 private messageHandler(
190 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
193 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
201 case ChargingStationWorkerMessageEvents
.STARTED
:
202 this.workerEventStarted(msg
.data
as ChargingStationData
);
204 case ChargingStationWorkerMessageEvents
.STOPPED
:
205 this.workerEventStopped(msg
.data
as ChargingStationData
);
207 case ChargingStationWorkerMessageEvents
.UPDATED
:
208 this.workerEventUpdated(msg
.data
as ChargingStationData
);
210 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
211 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
215 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
220 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
228 private workerEventStarted
= (data
: ChargingStationData
) => {
229 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
230 ++this.numberOfStartedChargingStations
;
232 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
233 data.stationInfo.chargingStationId
234 } (hashId: ${data.stationInfo.hashId}) started (${
235 this.numberOfStartedChargingStations
236 } started from ${this.numberOfChargingStations})`
240 private workerEventStopped
= (data
: ChargingStationData
) => {
241 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
242 --this.numberOfStartedChargingStations
;
244 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
245 data.stationInfo.chargingStationId
246 } (hashId: ${data.stationInfo.hashId}) stopped (${
247 this.numberOfStartedChargingStations
248 } started from ${this.numberOfChargingStations})`
252 private workerEventUpdated
= (data
: ChargingStationData
) => {
253 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
256 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
257 this.storage
.storePerformanceStatistics(data
) as void;
260 private initialize() {
261 this.numberOfChargingStationTemplates
= 0;
262 this.numberOfChargingStations
= 0;
263 this.numberOfStartedChargingStations
= 0;
264 this.initializeWorkerImplementation();
267 private logUncaughtException(): void {
268 process
.on('uncaughtException', (error
: Error) => {
269 console
.error(chalk
.red('Uncaught exception: '), error
);
273 private logUnhandledRejection(): void {
274 process
.on('unhandledRejection', (reason
: unknown
) => {
275 console
.error(chalk
.red('Unhandled rejection: '), reason
);
279 private async startChargingStation(
281 stationTemplateUrl
: StationTemplateUrl
283 const workerData
: ChargingStationWorkerData
= {
285 templateFile
: path
.join(
286 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
289 stationTemplateUrl
.file
292 await this.workerImplementation
.addElement(workerData
);
293 ++this.numberOfChargingStations
;
296 private logPrefix(): string {
297 return Utils
.logPrefix(' Bootstrap |');