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 UIServerFactory from
'./ui-server/UIServerFactory';
31 const moduleName
= 'Bootstrap';
33 const missingChargingStationsConfigurationExitCode
= 1;
34 const noChargingStationTemplatesExitCode
= 2;
36 export class Bootstrap
{
37 private static instance
: Bootstrap
| null = null;
38 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
39 private readonly uiServer
!: AbstractUIServer
;
40 private readonly storage
!: Storage
;
41 private numberOfChargingStationTemplates
!: number;
42 private numberOfChargingStations
!: number;
43 private numberOfStartedChargingStations
!: number;
44 private readonly version
: string = version
;
45 private started
: boolean;
46 private readonly workerScript
: string;
48 private constructor() {
50 this.workerScript
= path
.join(
51 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
53 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
56 Configuration
.getUIServer().enabled
=== true &&
57 (this.uiServer
= UIServerFactory
.getUIServerImplementation(
58 Configuration
.getUIServer().type,
59 Configuration
.getUIServer()
61 Configuration
.getPerformanceStorage().enabled
=== true &&
62 (this.storage
= StorageFactory
.getStorage(
63 Configuration
.getPerformanceStorage().type,
64 Configuration
.getPerformanceStorage().uri
,
67 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
70 public static getInstance(): Bootstrap
{
71 if (Bootstrap
.instance
=== null) {
72 Bootstrap
.instance
= new Bootstrap();
74 return Bootstrap
.instance
;
77 public async start(): Promise
<void> {
78 if (isMainThread
&& this.started
=== false) {
81 await this.storage
?.open();
82 await this.workerImplementation
.start();
83 this.uiServer
?.start();
84 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
85 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
86 // Start ChargingStation object in worker thread
87 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
88 for (const stationTemplateUrl
of stationTemplateUrls
) {
90 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
91 for (let index
= 1; index
<= nbStations
; index
++) {
92 await this.startChargingStation(index
, stationTemplateUrl
);
97 'Error at starting charging station with template file ' +
98 stationTemplateUrl
.file
+
107 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
109 process
.exit(missingChargingStationsConfigurationExitCode
);
111 if (this.numberOfChargingStations
=== 0) {
113 chalk
.yellow('No charging station template enabled in configuration, exiting')
115 process
.exit(noChargingStationTemplatesExitCode
);
119 `Charging stations simulator ${
121 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
122 ChargingStationUtils.workerDynamicPoolInUse()
123 ? `${Configuration.getWorker().poolMinSize.toString()}
/`
125 }${this.workerImplementation.size}${
126 ChargingStationUtils.workerPoolInUse()
127 ? `/${Configuration.getWorker().poolMaxSize.toString()}
`
129 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
130 this.workerImplementation.maxElementsPerWorker
131 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
139 console
.error(chalk
.red('Bootstrap start error: '), error
);
142 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
146 public async stop(): Promise
<void> {
147 if (isMainThread
&& this.started
=== true) {
148 await this.workerImplementation
.stop();
149 this.workerImplementation
= null;
150 this.uiServer
?.stop();
151 await this.storage
?.close();
153 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
155 this.started
= false;
158 public async restart(): Promise
<void> {
164 private initializeWorkerImplementation(): void {
165 !this.workerImplementation
&&
166 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
168 Configuration
.getWorker().processType
,
170 workerStartDelay
: Configuration
.getWorker().startDelay
,
171 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
172 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
173 poolMinSize
: Configuration
.getWorker().poolMinSize
,
174 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
176 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
178 messageHandler
: this.messageHandler
.bind(this) as (
179 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
185 private messageHandler(
186 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
189 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
197 case ChargingStationWorkerMessageEvents
.STARTED
:
198 this.workerEventStarted(msg
.data
as ChargingStationData
);
200 case ChargingStationWorkerMessageEvents
.STOPPED
:
201 this.workerEventStopped(msg
.data
as ChargingStationData
);
203 case ChargingStationWorkerMessageEvents
.UPDATED
:
204 this.workerEventUpdated(msg
.data
as ChargingStationData
);
206 case ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
:
207 this.workerEventPerformanceStatistics(msg
.data
as Statistics
);
211 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
216 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
224 private workerEventStarted(data
: ChargingStationData
) {
225 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
226 ++this.numberOfStartedChargingStations
;
229 private workerEventStopped(data
: ChargingStationData
) {
230 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
231 --this.numberOfStartedChargingStations
;
234 private workerEventUpdated(data
: ChargingStationData
) {
235 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
238 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
239 this.storage
.storePerformanceStatistics(data
) as void;
242 private initialize() {
243 this.numberOfChargingStationTemplates
= 0;
244 this.numberOfChargingStations
= 0;
245 this.numberOfStartedChargingStations
= 0;
246 this.initializeWorkerImplementation();
249 private async startChargingStation(
251 stationTemplateUrl
: StationTemplateUrl
253 const workerData
: ChargingStationWorkerData
= {
255 templateFile
: path
.join(
256 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
259 stationTemplateUrl
.file
262 await this.workerImplementation
.addElement(workerData
);
263 ++this.numberOfChargingStations
;
266 private logPrefix(): string {
267 return Utils
.logPrefix(' Bootstrap |');