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 { 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 { StationTemplateUrl
} from
'../types/ConfigurationData';
21 import Statistics from
'../types/Statistics';
22 import { ApplicationProtocol
} from
'../types/UIProtocol';
23 import Configuration from
'../utils/Configuration';
24 import logger from
'../utils/Logger';
25 import Utils from
'../utils/Utils';
26 import WorkerAbstract from
'../worker/WorkerAbstract';
27 import WorkerFactory from
'../worker/WorkerFactory';
28 import { ChargingStationUtils
} from
'./ChargingStationUtils';
29 import { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
30 import { UIServiceUtils
} from
'./ui-server/ui-services/UIServiceUtils';
31 import UIServerFactory from
'./ui-server/UIServerFactory';
33 const moduleName
= 'Bootstrap';
35 const missingChargingStationsConfigurationExitCode
= 1;
36 const noChargingStationTemplatesExitCode
= 2;
38 export class Bootstrap
{
39 private static instance
: Bootstrap
| null = null;
40 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = 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.workerScript
= path
.join(
53 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
55 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
58 Configuration
.getUIServer().enabled
&&
59 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
60 ...Configuration
.getUIServer().options
,
61 handleProtocols
: UIServiceUtils
.handleProtocols
,
63 Configuration
.getPerformanceStorage().enabled
&&
64 (this.storage
= StorageFactory
.getStorage(
65 Configuration
.getPerformanceStorage().type,
66 Configuration
.getPerformanceStorage().uri
,
69 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
72 public static getInstance(): Bootstrap
{
73 if (Bootstrap
.instance
=== null) {
74 Bootstrap
.instance
= new Bootstrap();
76 return Bootstrap
.instance
;
79 public async start(): Promise
<void> {
80 if (isMainThread
&& !this.started
) {
83 await this.storage
?.open();
84 await this.workerImplementation
.start();
85 this.uiServer
?.start();
86 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
87 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
88 // Start ChargingStation object in worker thread
89 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
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 ' +
100 stationTemplateUrl
.file
+
109 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
111 process
.exit(missingChargingStationsConfigurationExitCode
);
113 if (this.numberOfChargingStations
=== 0) {
115 chalk
.yellow('No charging station template enabled in configuration, exiting')
117 process
.exit(noChargingStationTemplatesExitCode
);
121 `Charging stations simulator ${
123 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
124 ChargingStationUtils.workerDynamicPoolInUse()
125 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
127 }${this.workerImplementation.size}${
128 ChargingStationUtils.workerPoolInUse()
129 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
131 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
132 this.workerImplementation.maxElementsPerWorker
133 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
141 console
.error(chalk
.red('Bootstrap start error '), error
);
144 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
148 public async stop(): Promise
<void> {
149 if (isMainThread
&& this.started
) {
150 await this.workerImplementation
.stop();
151 this.workerImplementation
= null;
152 this.uiServer
?.stop();
153 await this.storage
?.close();
155 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
157 this.started
= false;
160 public async restart(): Promise
<void> {
166 private initializeWorkerImplementation(): void {
167 !this.workerImplementation
&&
168 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
170 Configuration
.getWorker().processType
,
172 workerStartDelay
: Configuration
.getWorker().startDelay
,
173 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
174 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
175 poolMinSize
: Configuration
.getWorker().poolMinSize
,
176 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
178 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
180 messageHandler
: this.messageHandler
.bind(this) as (
181 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
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
.hashId
, data
);
228 ++this.numberOfStartedChargingStations
;
231 private workerEventStopped(data
: ChargingStationData
) {
232 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
233 --this.numberOfStartedChargingStations
;
236 private workerEventUpdated(data
: ChargingStationData
) {
237 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
240 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
241 this.storage
.storePerformanceStatistics(data
) as void;
244 private initialize() {
245 this.numberOfChargingStationTemplates
= 0;
246 this.numberOfChargingStations
= 0;
247 this.numberOfStartedChargingStations
= 0;
248 this.initializeWorkerImplementation();
251 private async startChargingStation(
253 stationTemplateUrl
: StationTemplateUrl
255 const workerData
: ChargingStationWorkerData
= {
257 templateFile
: path
.join(
258 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
261 stationTemplateUrl
.file
264 await this.workerImplementation
.addElement(workerData
);
265 ++this.numberOfChargingStations
;
268 private logPrefix(): string {
269 return Utils
.logPrefix(' Bootstrap |');