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 ChargingStationWorkerMessageEvents
,
18 } from
'../types/ChargingStationWorker';
19 import { StationTemplateUrl
} from
'../types/ConfigurationData';
20 import Statistics from
'../types/Statistics';
21 import { ApplicationProtocol
} from
'../types/UIProtocol';
22 import Configuration from
'../utils/Configuration';
23 import logger from
'../utils/Logger';
24 import Utils from
'../utils/Utils';
25 import WorkerAbstract from
'../worker/WorkerAbstract';
26 import WorkerFactory from
'../worker/WorkerFactory';
27 import { ChargingStationUtils
} from
'./ChargingStationUtils';
28 import { 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 export default class Bootstrap
{
35 private static instance
: Bootstrap
| null = null;
36 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
37 private readonly uiServer
!: AbstractUIServer
;
38 private readonly storage
!: Storage
;
39 private numberOfChargingStationTemplates
!: number;
40 private numberOfChargingStations
!: number;
41 private readonly version
: string = version
;
42 private started
: boolean;
43 private readonly workerScript
: string;
45 private constructor() {
47 this.workerScript
= path
.join(
48 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
50 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
53 Configuration
.getUIServer().enabled
&&
54 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
55 ...Configuration
.getUIServer().options
,
56 handleProtocols
: UIServiceUtils
.handleProtocols
,
58 Configuration
.getPerformanceStorage().enabled
&&
59 (this.storage
= StorageFactory
.getStorage(
60 Configuration
.getPerformanceStorage().type,
61 Configuration
.getPerformanceStorage().uri
,
64 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
67 public static getInstance(): Bootstrap
{
68 if (Bootstrap
.instance
=== null) {
69 Bootstrap
.instance
= new Bootstrap();
71 return Bootstrap
.instance
;
74 public async start(): Promise
<void> {
75 if (isMainThread
&& !this.started
) {
78 await this.storage
?.open();
79 await this.workerImplementation
.start();
80 this.uiServer
?.start();
81 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
82 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
83 // Start ChargingStation object in worker thread
84 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
85 for (const stationTemplateUrl
of stationTemplateUrls
) {
87 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
88 for (let index
= 1; index
<= nbStations
; index
++) {
89 await this.startChargingStation(index
, stationTemplateUrl
);
94 'Error at starting charging station with template file ' +
95 stationTemplateUrl
.file
+
104 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
107 if (this.numberOfChargingStations
=== 0) {
109 chalk
.yellow('No charging station template enabled in configuration, exiting')
115 `Charging stations simulator ${
117 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
118 ChargingStationUtils.workerDynamicPoolInUse()
119 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
121 }${this.workerImplementation.size}${
122 ChargingStationUtils.workerPoolInUse()
123 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
125 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
126 this.workerImplementation.maxElementsPerWorker
127 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
135 console
.error(chalk
.red('Bootstrap start error '), error
);
138 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
142 public async stop(): Promise
<void> {
143 if (isMainThread
&& this.started
) {
144 await this.workerImplementation
.stop();
145 this.workerImplementation
= null;
146 this.uiServer
?.stop();
147 await this.storage
?.close();
149 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
151 this.started
= false;
154 public async restart(): Promise
<void> {
160 private initializeWorkerImplementation(): void {
161 !this.workerImplementation
&&
162 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
164 Configuration
.getWorker().processType
,
166 workerStartDelay
: Configuration
.getWorker().startDelay
,
167 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
168 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
169 poolMinSize
: Configuration
.getWorker().poolMinSize
,
170 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
172 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
174 messageHandler
: this.messageHandler
.bind(this) as (
175 msg
: ChargingStationWorkerMessage
<ChargingStationData
| Statistics
>
181 private messageHandler(
182 msg
: ChargingStationWorkerMessage
<ChargingStationData
| Statistics
>
185 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
193 case ChargingStationWorkerMessageEvents
.STARTED
:
194 this.workerEventStarted(msg
.data
as ChargingStationData
);
196 case ChargingStationWorkerMessageEvents
.STOPPED
:
197 this.workerEventStopped(msg
.data
as ChargingStationData
);
199 case ChargingStationWorkerMessageEvents
.UPDATED
:
200 this.workerEventUpdated(msg
.data
as ChargingStationData
);
202 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
203 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
207 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
212 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
220 private workerEventStarted(data
: ChargingStationData
) {
221 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
222 this.started
&& ++this.numberOfChargingStations
;
225 private workerEventStopped(data
: ChargingStationData
) {
226 this.uiServer
?.chargingStations
.delete(data
.hashId
);
227 this.started
&& --this.numberOfChargingStations
;
230 private workerEventUpdated(data
: ChargingStationData
) {
231 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
234 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
235 this.storage
.storePerformanceStatistics(data
) as void;
238 private initialize() {
239 this.numberOfChargingStations
= 0;
240 this.numberOfChargingStationTemplates
= 0;
241 this.initializeWorkerImplementation();
244 private async startChargingStation(
246 stationTemplateUrl
: StationTemplateUrl
248 const workerData
: ChargingStationWorkerData
= {
250 templateFile
: path
.join(
251 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
254 stationTemplateUrl
.file
257 await this.workerImplementation
.addElement(workerData
);
258 this.numberOfChargingStations
++;
261 private logPrefix(): string {
262 return Utils
.logPrefix(' Bootstrap |');