1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ChargingStationWorkerData
, ChargingStationWorkerMessage
, ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
5 import Configuration from
'../utils/Configuration';
6 import { Storage
} from
'../performance/storage/Storage';
7 import { StorageFactory
} from
'../performance/storage/StorageFactory';
8 import { UIServiceUtils
} from
'./ui-websocket-services/UIServiceUtils';
9 import UIWebSocketServer from
'./UIWebSocketServer';
10 import Utils from
'../utils/Utils';
11 import WorkerAbstract from
'../worker/WorkerAbstract';
12 import WorkerFactory from
'../worker/WorkerFactory';
13 import chalk from
'chalk';
14 import { isMainThread
} from
'worker_threads';
15 import path from
'path';
16 import { version
} from
'../../package.json';
18 export default class Bootstrap
{
19 private static instance
: Bootstrap
| null = null;
20 private workerImplementation
: WorkerAbstract
| null = null;
21 private readonly uiWebSocketServer
!: UIWebSocketServer
;
22 private readonly storage
!: Storage
;
23 private numberOfChargingStations
: number;
24 private readonly version
: string = version
;
25 private started
: boolean;
26 private readonly workerScript
: string;
28 private constructor() {
30 this.workerScript
= path
.join(path
.resolve(__dirname
, '../'), 'charging-station', 'ChargingStationWorker.js');
31 this.initWorkerImplementation();
32 Configuration
.getUIWebSocketServer().enabled
&& (this.uiWebSocketServer
= new UIWebSocketServer({
33 ...Configuration
.getUIWebSocketServer().options
, handleProtocols
: UIServiceUtils
.handleProtocols
35 Configuration
.getPerformanceStorage().enabled
&& (this.storage
= StorageFactory
.getStorage(
36 Configuration
.getPerformanceStorage().type,
37 Configuration
.getPerformanceStorage().uri
,
40 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
43 public static getInstance(): Bootstrap
{
44 if (!Bootstrap
.instance
) {
45 Bootstrap
.instance
= new Bootstrap();
47 return Bootstrap
.instance
;
50 public async start(): Promise
<void> {
51 if (isMainThread
&& !this.started
) {
53 this.numberOfChargingStations
= 0;
54 await this.storage
?.open();
55 await this.workerImplementation
.start();
56 this.uiWebSocketServer
?.start();
57 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
58 // Start ChargingStation object in worker thread
59 if (stationTemplateUrls
) {
60 for (const stationTemplateUrl
of stationTemplateUrls
) {
62 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
63 for (let index
= 1; index
<= nbStations
; index
++) {
64 const workerData
: ChargingStationWorkerData
= {
66 templateFile
: path
.join(path
.resolve(__dirname
, '../'), 'assets', 'station-templates', path
.basename(stationTemplateUrl
.file
))
68 await this.workerImplementation
.addElement(workerData
);
69 this.numberOfChargingStations
++;
72 console
.error(chalk
.red('Charging station start with template file ' + stationTemplateUrl
.file
+ ' error '), error
);
76 console
.warn(chalk
.yellow('No stationTemplateUrls defined in configuration, exiting'));
78 if (this.numberOfChargingStations
=== 0) {
79 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
81 console
.log(chalk
.green(`Charging stations simulator ${this.version} started with ${this.numberOfChargingStations.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}
` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.workerImplementation.maxElementsPerWorker ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`));
85 console.error(chalk.red('Bootstrap start error '), error);
88 console.error(chalk.red('Cannot start an already started charging stations simulator'));
92 public async stop(): Promise<void> {
93 if (isMainThread && this.started) {
94 await this.workerImplementation.stop();
95 this.uiWebSocketServer?.stop();
96 await this.storage?.close();
98 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
100 this.started = false;
103 public async restart(): Promise<void> {
105 this.initWorkerImplementation();
109 private initWorkerImplementation(): void {
110 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
112 startDelay: Configuration.getWorkerStartDelay(),
113 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
114 poolMinSize: Configuration.getWorkerPoolMinSize(),
115 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
117 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
119 messageHandler: async (msg: ChargingStationWorkerMessage) => {
120 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
121 this.uiWebSocketServer.chargingStations.add(msg.data.id);
122 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
123 this.uiWebSocketServer.chargingStations.delete(msg.data.id);
124 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
125 await this.storage.storePerformanceStatistics(msg.data);
131 private logPrefix(): string {
132 return Utils.logPrefix(' Bootstrap |');