1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import path from
'path';
4 import { fileURLToPath
} from
'url';
5 import { 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 { UIServiceUtils
} from
'./ui-server/ui-services/UIServiceUtils';
30 import UIServerFactory from
'./ui-server/UIServerFactory';
32 const moduleName
= 'Bootstrap';
34 const missingChargingStationsConfigurationExitCode
= 1;
35 const noChargingStationTemplatesExitCode
= 2;
37 export class Bootstrap
{
38 private static instance
: Bootstrap
| null = null;
39 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
40 private readonly uiServer
!: AbstractUIServer
;
41 private readonly storage
!: Storage
;
42 private numberOfChargingStationTemplates
!: number;
43 private numberOfChargingStations
!: number;
44 private numberOfStartedChargingStations
!: number;
45 private readonly version
: string = version
;
46 private started
: boolean;
47 private readonly workerScript
: string;
49 private constructor() {
51 this.workerScript
= path
.join(
52 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
54 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
57 Configuration
.getUIServer().enabled
&&
58 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer().type, {
59 ...Configuration
.getUIServer().options
,
60 handleProtocols
: UIServiceUtils
.handleProtocols
,
62 Configuration
.getPerformanceStorage().enabled
&&
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
) {
82 await this.storage
?.open();
83 await this.workerImplementation
.start();
84 this.uiServer
?.start();
85 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
86 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
87 // Start ChargingStation object in worker thread
88 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
89 for (const stationTemplateUrl
of stationTemplateUrls
) {
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 ' +
99 stationTemplateUrl
.file
+
108 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
110 process
.exit(missingChargingStationsConfigurationExitCode
);
112 if (this.numberOfChargingStations
=== 0) {
114 chalk
.yellow('No charging station template enabled in configuration, exiting')
116 process
.exit(noChargingStationTemplatesExitCode
);
120 `Charging stations simulator ${
122 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
123 ChargingStationUtils.workerDynamicPoolInUse()
124 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
126 }${this.workerImplementation.size}${
127 ChargingStationUtils.workerPoolInUse()
128 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
130 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
131 this.workerImplementation.maxElementsPerWorker
132 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
140 console
.error(chalk
.red('Bootstrap start error '), error
);
143 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
147 public async stop(): Promise
<void> {
148 if (isMainThread
&& this.started
) {
149 await this.workerImplementation
.stop();
150 this.workerImplementation
= null;
151 this.uiServer
?.stop();
152 await this.storage
?.close();
154 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
156 this.started
= false;
159 public async restart(): Promise
<void> {
165 private initializeWorkerImplementation(): void {
166 !this.workerImplementation
&&
167 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
169 Configuration
.getWorker().processType
,
171 workerStartDelay
: Configuration
.getWorker().startDelay
,
172 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
173 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
174 poolMinSize
: Configuration
.getWorker().poolMinSize
,
175 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
177 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
179 messageHandler
: this.messageHandler
.bind(this) as (
180 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
186 private messageHandler(
187 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
190 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
198 case ChargingStationWorkerMessageEvents
.STARTED
:
199 this.workerEventStarted(msg
.data
as ChargingStationData
);
201 case ChargingStationWorkerMessageEvents
.STOPPED
:
202 this.workerEventStopped(msg
.data
as ChargingStationData
);
204 case ChargingStationWorkerMessageEvents
.UPDATED
:
205 this.workerEventUpdated(msg
.data
as ChargingStationData
);
207 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
208 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
212 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
217 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
225 private workerEventStarted(data
: ChargingStationData
) {
226 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
227 ++this.numberOfStartedChargingStations
;
230 private workerEventStopped(data
: ChargingStationData
) {
231 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
232 --this.numberOfStartedChargingStations
;
235 private workerEventUpdated(data
: ChargingStationData
) {
236 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
239 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
240 this.storage
.storePerformanceStatistics(data
) as void;
243 private initialize() {
244 this.numberOfChargingStationTemplates
= 0;
245 this.numberOfChargingStations
= 0;
246 this.numberOfStartedChargingStations
= 0;
247 this.initializeWorkerImplementation();
250 private async startChargingStation(
252 stationTemplateUrl
: StationTemplateUrl
254 const workerData
: ChargingStationWorkerData
= {
256 templateFile
: path
.join(
257 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
260 stationTemplateUrl
.file
263 await this.workerImplementation
.addElement(workerData
);
264 ++this.numberOfChargingStations
;
267 private logPrefix(): string {
268 return Utils
.logPrefix(' Bootstrap |');