1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 ChargingStationWorkerData
,
5 ChargingStationWorkerMessage
,
6 ChargingStationWorkerMessageEvents
,
7 } from
'../types/ChargingStationWorker';
9 import { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
10 import { ApplicationProtocol
} from
'../types/UIProtocol';
11 import { ChargingStationUtils
} from
'./ChargingStationUtils';
12 import Configuration from
'../utils/Configuration';
13 import { StationTemplateUrl
} from
'../types/ConfigurationData';
14 import Statistics from
'../types/Statistics';
15 import { Storage
} from
'../performance/storage/Storage';
16 import { StorageFactory
} from
'../performance/storage/StorageFactory';
17 import UIServerFactory from
'./ui-server/UIServerFactory';
18 import { UIServiceUtils
} from
'./ui-server/ui-services/UIServiceUtils';
19 import Utils from
'../utils/Utils';
20 import WorkerAbstract from
'../worker/WorkerAbstract';
21 import WorkerFactory from
'../worker/WorkerFactory';
22 import chalk from
'chalk';
23 import { fileURLToPath
} from
'url';
24 import { isMainThread
} from
'worker_threads';
25 import path from
'path';
26 import { version
} from
'../../package.json';
28 export default class Bootstrap
{
29 private static instance
: Bootstrap
| null = null;
30 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
31 private readonly uiServer
!: AbstractUIServer
;
32 private readonly storage
!: Storage
;
33 private numberOfChargingStationTemplates
!: number;
34 private numberOfChargingStations
!: number;
35 private readonly version
: string = version
;
36 private started
: boolean;
37 private readonly workerScript
: string;
39 private constructor() {
41 this.workerScript
= path
.join(
42 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
44 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
47 this.initWorkerImplementation();
48 Configuration
.getUIServer().enabled
&&
49 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
50 ...Configuration
.getUIServer().options
,
51 handleProtocols
: UIServiceUtils
.handleProtocols
,
53 Configuration
.getPerformanceStorage().enabled
&&
54 (this.storage
= StorageFactory
.getStorage(
55 Configuration
.getPerformanceStorage().type,
56 Configuration
.getPerformanceStorage().uri
,
59 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
62 public static getInstance(): Bootstrap
{
63 if (!Bootstrap
.instance
) {
64 Bootstrap
.instance
= new Bootstrap();
66 return Bootstrap
.instance
;
69 public async start(): Promise
<void> {
70 if (isMainThread
&& !this.started
) {
73 await this.storage
?.open();
74 await this.workerImplementation
.start();
75 this.uiServer
?.start();
76 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
77 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
78 // Start ChargingStation object in worker thread
79 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
80 for (const stationTemplateUrl
of stationTemplateUrls
) {
82 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
83 for (let index
= 1; index
<= nbStations
; index
++) {
84 await this.startChargingStation(index
, stationTemplateUrl
);
89 'Error at starting charging station with template file ' +
90 stationTemplateUrl
.file
+
99 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
102 if (this.numberOfChargingStations
=== 0) {
104 chalk
.yellow('No charging station template enabled in configuration, exiting')
109 `Charging stations simulator ${
111 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
112 ChargingStationUtils.workerDynamicPoolInUse()
113 ? `${Configuration.getWorkerPoolMinSize().toString()}
/`
115 }${this.workerImplementation.size}${
116 ChargingStationUtils.workerPoolInUse()
117 ? `/${Configuration.getWorkerPoolMaxSize().toString()}
`
119 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
120 this.workerImplementation.maxElementsPerWorker
121 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
129 console
.error(chalk
.red('Bootstrap start error '), error
);
132 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
136 public async stop(): Promise
<void> {
137 if (isMainThread
&& this.started
) {
138 await this.workerImplementation
.stop();
139 this.uiServer
?.stop();
140 await this.storage
?.close();
142 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
144 this.started
= false;
147 public async restart(): Promise
<void> {
150 this.initWorkerImplementation();
154 private initWorkerImplementation(): void {
155 this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
157 Configuration
.getWorkerProcess(),
159 workerStartDelay
: Configuration
.getWorkerStartDelay(),
160 elementStartDelay
: Configuration
.getElementStartDelay(),
161 poolMaxSize
: Configuration
.getWorkerPoolMaxSize(),
162 poolMinSize
: Configuration
.getWorkerPoolMinSize(),
163 elementsPerWorker
: Configuration
.getChargingStationsPerWorker(),
165 workerChoiceStrategy
: Configuration
.getWorkerPoolStrategy(),
167 messageHandler
: async (msg
: ChargingStationWorkerMessage
) => {
168 if (msg
.id
=== ChargingStationWorkerMessageEvents
.STARTED
) {
169 this.uiServer
.chargingStations
.add(msg
.data
.id
as string);
170 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.STOPPED
) {
171 this.uiServer
.chargingStations
.delete(msg
.data
.id
as string);
172 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
) {
173 await this.storage
.storePerformanceStatistics(msg
.data
as unknown
as Statistics
);
180 private initialize() {
181 this.numberOfChargingStations
= 0;
182 this.numberOfChargingStationTemplates
= 0;
185 private async startChargingStation(
187 stationTemplateUrl
: StationTemplateUrl
189 const workerData
: ChargingStationWorkerData
= {
191 templateFile
: path
.join(
192 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
195 path
.basename(stationTemplateUrl
.file
)
198 await this.workerImplementation
.addElement(workerData
);
199 this.numberOfChargingStations
++;
202 private logPrefix(): string {
203 return Utils
.logPrefix(' Bootstrap |');