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 export default class Bootstrap
{
36 private static instance
: Bootstrap
| null = null;
37 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
38 private readonly uiServer
!: AbstractUIServer
;
39 private readonly storage
!: Storage
;
40 private numberOfChargingStationTemplates
!: number;
41 private numberOfChargingStations
!: number;
42 private numberOfStartedChargingStations
!: number;
43 private readonly version
: string = version
;
44 private started
: boolean;
45 private readonly workerScript
: string;
47 private constructor() {
49 this.workerScript
= path
.join(
50 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
52 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
55 Configuration
.getUIServer().enabled
&&
56 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
57 ...Configuration
.getUIServer().options
,
58 handleProtocols
: UIServiceUtils
.handleProtocols
,
60 Configuration
.getPerformanceStorage().enabled
&&
61 (this.storage
= StorageFactory
.getStorage(
62 Configuration
.getPerformanceStorage().type,
63 Configuration
.getPerformanceStorage().uri
,
66 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
69 public static getInstance(): Bootstrap
{
70 if (Bootstrap
.instance
=== null) {
71 Bootstrap
.instance
= new Bootstrap();
73 return Bootstrap
.instance
;
76 public async start(): Promise
<void> {
77 if (isMainThread
&& !this.started
) {
80 await this.storage
?.open();
81 await this.workerImplementation
.start();
82 this.uiServer
?.start();
83 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
84 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
85 // Start ChargingStation object in worker thread
86 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
87 for (const stationTemplateUrl
of stationTemplateUrls
) {
89 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
90 for (let index
= 1; index
<= nbStations
; index
++) {
91 await this.startChargingStation(index
, stationTemplateUrl
);
96 'Error at starting charging station with template file ' +
97 stationTemplateUrl
.file
+
106 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
109 if (this.numberOfChargingStations
=== 0) {
111 chalk
.yellow('No charging station template enabled in configuration, exiting')
117 `Charging stations simulator ${
119 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
120 ChargingStationUtils.workerDynamicPoolInUse()
121 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
123 }${this.workerImplementation.size}${
124 ChargingStationUtils.workerPoolInUse()
125 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
127 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
128 this.workerImplementation.maxElementsPerWorker
129 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
137 console
.error(chalk
.red('Bootstrap start error '), error
);
140 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
144 public async stop(): Promise
<void> {
145 if (isMainThread
&& this.started
) {
146 await this.workerImplementation
.stop();
147 this.workerImplementation
= null;
148 this.uiServer
?.stop();
149 await this.storage
?.close();
151 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
153 this.started
= false;
156 public async restart(): Promise
<void> {
162 private initializeWorkerImplementation(): void {
163 !this.workerImplementation
&&
164 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
166 Configuration
.getWorker().processType
,
168 workerStartDelay
: Configuration
.getWorker().startDelay
,
169 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
170 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
171 poolMinSize
: Configuration
.getWorker().poolMinSize
,
172 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
174 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
176 messageHandler
: this.messageHandler
.bind(this) as (
177 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
183 private messageHandler(
184 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
187 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
195 case ChargingStationWorkerMessageEvents
.STARTED
:
196 this.workerEventStarted(msg
.data
as ChargingStationData
);
198 case ChargingStationWorkerMessageEvents
.STOPPED
:
199 this.workerEventStopped(msg
.data
as ChargingStationData
);
201 case ChargingStationWorkerMessageEvents
.UPDATED
:
202 this.workerEventUpdated(msg
.data
as ChargingStationData
);
204 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
205 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
209 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
214 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
222 private workerEventStarted(data
: ChargingStationData
) {
223 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
224 ++this.numberOfStartedChargingStations
;
227 private workerEventStopped(data
: ChargingStationData
) {
228 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
229 --this.numberOfStartedChargingStations
;
232 private workerEventUpdated(data
: ChargingStationData
) {
233 this.uiServer
?.chargingStations
.set(data
.hashId
, data
);
236 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
237 this.storage
.storePerformanceStatistics(data
) as void;
240 private initialize() {
241 this.numberOfChargingStationTemplates
= 0;
242 this.numberOfChargingStations
= 0;
243 this.numberOfStartedChargingStations
= 0;
244 this.initializeWorkerImplementation();
247 private async startChargingStation(
249 stationTemplateUrl
: StationTemplateUrl
251 const workerData
: ChargingStationWorkerData
= {
253 templateFile
: path
.join(
254 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
257 stationTemplateUrl
.file
260 await this.workerImplementation
.addElement(workerData
);
261 ++this.numberOfChargingStations
;
264 private logPrefix(): string {
265 return Utils
.logPrefix(' Bootstrap |');