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 numberOfStartedChargingStations
!: number;
42 private readonly version
: string = version
;
43 private started
: boolean;
44 private readonly workerScript
: string;
46 private constructor() {
48 this.workerScript
= path
.join(
49 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
51 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
54 Configuration
.getUIServer().enabled
&&
55 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
56 ...Configuration
.getUIServer().options
,
57 handleProtocols
: UIServiceUtils
.handleProtocols
,
59 Configuration
.getPerformanceStorage().enabled
&&
60 (this.storage
= StorageFactory
.getStorage(
61 Configuration
.getPerformanceStorage().type,
62 Configuration
.getPerformanceStorage().uri
,
65 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
68 public static getInstance(): Bootstrap
{
69 if (Bootstrap
.instance
=== null) {
70 Bootstrap
.instance
= new Bootstrap();
72 return Bootstrap
.instance
;
75 public async start(): Promise
<void> {
76 if (isMainThread
&& !this.started
) {
79 await this.storage
?.open();
80 await this.workerImplementation
.start();
81 this.uiServer
?.start();
82 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
83 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
84 // Start ChargingStation object in worker thread
85 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
86 for (const stationTemplateUrl
of stationTemplateUrls
) {
88 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
89 for (let index
= 1; index
<= nbStations
; index
++) {
90 await this.startChargingStation(index
, stationTemplateUrl
);
95 'Error at starting charging station with template file ' +
96 stationTemplateUrl
.file
+
105 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
108 if (this.numberOfChargingStations
=== 0) {
110 chalk
.yellow('No charging station template enabled in configuration, exiting')
116 `Charging stations simulator ${
118 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
119 ChargingStationUtils.workerDynamicPoolInUse()
120 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
122 }${this.workerImplementation.size}${
123 ChargingStationUtils.workerPoolInUse()
124 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
126 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
127 this.workerImplementation.maxElementsPerWorker
128 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
136 console
.error(chalk
.red('Bootstrap start error '), error
);
139 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
143 public async stop(): Promise
<void> {
144 if (isMainThread
&& this.started
) {
145 await this.workerImplementation
.stop();
146 this.workerImplementation
= null;
147 this.uiServer
?.stop();
148 await this.storage
?.close();
150 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
152 this.started
= false;
155 public async restart(): Promise
<void> {
161 private initializeWorkerImplementation(): void {
162 !this.workerImplementation
&&
163 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
165 Configuration
.getWorker().processType
,
167 workerStartDelay
: Configuration
.getWorker().startDelay
,
168 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
169 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
170 poolMinSize
: Configuration
.getWorker().poolMinSize
,
171 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
173 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
175 messageHandler
: this.messageHandler
.bind(this) as (
176 msg
: ChargingStationWorkerMessage
<ChargingStationData
| Statistics
>
182 private messageHandler(
183 msg
: ChargingStationWorkerMessage
<ChargingStationData
| Statistics
>
186 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
194 case ChargingStationWorkerMessageEvents
.STARTED
:
195 this.workerEventStarted(msg
.data
as ChargingStationData
);
197 case ChargingStationWorkerMessageEvents
.STOPPED
:
198 this.workerEventStopped(msg
.data
as ChargingStationData
);
200 case ChargingStationWorkerMessageEvents
.UPDATED
:
201 this.workerEventUpdated(msg
.data
as ChargingStationData
);
203 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
204 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
208 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
213 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
221 private workerEventStarted(data
: ChargingStationData
) {
222 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
223 ++this.numberOfStartedChargingStations
;
226 private workerEventStopped(data
: ChargingStationData
) {
227 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
228 --this.numberOfStartedChargingStations
;
231 private workerEventUpdated(data
: ChargingStationData
) {
232 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
235 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
236 this.storage
.storePerformanceStatistics(data
) as void;
239 private initialize() {
240 this.numberOfChargingStationTemplates
= 0;
241 this.numberOfChargingStations
= 0;
242 this.numberOfStartedChargingStations
= 0;
243 this.initializeWorkerImplementation();
246 private async startChargingStation(
248 stationTemplateUrl
: StationTemplateUrl
250 const workerData
: ChargingStationWorkerData
= {
252 templateFile
: path
.join(
253 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
256 stationTemplateUrl
.file
259 await this.workerImplementation
.addElement(workerData
);
260 ++this.numberOfChargingStations
;
263 private logPrefix(): string {
264 return Utils
.logPrefix(' Bootstrap |');