1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 ChargingStationWorkerData
,
5 ChargingStationWorkerMessage
,
6 ChargingStationWorkerMessageEvents
,
7 } from
'../types/ChargingStationWorker';
9 import Configuration from
'../utils/Configuration';
10 import { StationTemplateUrl
} from
'../types/ConfigurationData';
11 import Statistics from
'../types/Statistics';
12 import { Storage
} from
'../performance/storage/Storage';
13 import { StorageFactory
} from
'../performance/storage/StorageFactory';
14 import { UIServiceUtils
} from
'./ui-websocket-services/UIServiceUtils';
15 import UIWebSocketServer from
'./UIWebSocketServer';
16 import Utils from
'../utils/Utils';
17 import WorkerAbstract from
'../worker/WorkerAbstract';
18 import WorkerFactory from
'../worker/WorkerFactory';
19 import chalk from
'chalk';
20 import { isMainThread
} from
'worker_threads';
21 import path from
'path';
22 import { version
} from
'../../package.json';
24 export default class Bootstrap
{
25 private static instance
: Bootstrap
| null = null;
26 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
27 private readonly uiWebSocketServer
!: UIWebSocketServer
;
28 private readonly storage
!: Storage
;
29 private numberOfChargingStations
: number;
30 private readonly version
: string = version
;
31 private started
: boolean;
32 private readonly workerScript
: string;
34 private constructor() {
36 this.workerScript
= path
.join(
37 // wouldn't path.resolve(./ChargingStationWorker.js) faster & simpler ?
38 path
.resolve(__dirname
, '../'),
40 'ChargingStationWorker.js'
42 this.initWorkerImplementation(); // init thread
43 Configuration
.getUIWebSocketServer().enabled
&& // create webSocket
44 (this.uiWebSocketServer
= new UIWebSocketServer({
45 ...Configuration
.getUIWebSocketServer().options
,
46 handleProtocols
: UIServiceUtils
.handleProtocols
,
48 Configuration
.getPerformanceStorage().enabled
&& // create storage ??? but for what
49 (this.storage
= StorageFactory
.getStorage(
50 Configuration
.getPerformanceStorage().type,
51 Configuration
.getPerformanceStorage().uri
,
54 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
57 public static getInstance(): Bootstrap
{
58 if (!Bootstrap
.instance
) {
59 Bootstrap
.instance
= new Bootstrap();
61 return Bootstrap
.instance
;
64 public async start(): Promise
<void> {
65 if (isMainThread
&& !this.started
) {
67 this.numberOfChargingStations
= 0;
68 await this.storage
?.open();
69 await this.workerImplementation
.start();
70 this.uiWebSocketServer
?.start();
71 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
72 // Start ChargingStation object in worker thread
73 if (stationTemplateUrls
) {
74 for (const stationTemplateUrl
of stationTemplateUrls
) {
76 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
77 for (let index
= 1; index
<= nbStations
; index
++) {
78 await this.startChargingStation(index
, stationTemplateUrl
);
83 'Charging station start with template file ' + stationTemplateUrl
.file
+ ' error '
90 console
.warn(chalk
.yellow('No stationTemplateUrls defined in configuration, exiting'));
92 if (this.numberOfChargingStations
=== 0) {
94 chalk
.yellow('No charging station template enabled in configuration, exiting')
99 `Charging stations simulator ${
101 } started with ${this.numberOfChargingStations.toString()} charging station(s) and ${
102 Utils.workerDynamicPoolInUse()
103 ? `${Configuration.getWorkerPoolMinSize().toString()}
/`
105 }${this.workerImplementation.size}${
106 Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}
` : ''
107 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
108 this.workerImplementation.maxElementsPerWorker
109 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
117 console
.error(chalk
.red('Bootstrap start error '), error
);
120 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
124 public async stop(): Promise
<void> {
125 if (isMainThread
&& this.started
) {
126 await this.workerImplementation
.stop();
127 this.uiWebSocketServer
?.stop();
128 await this.storage
?.close();
130 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
132 this.started
= false;
135 public async restart(): Promise
<void> {
137 this.initWorkerImplementation();
141 private initWorkerImplementation(): void {
142 this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
144 Configuration
.getWorkerProcess(),
146 workerStartDelay
: Configuration
.getWorkerStartDelay(),
147 elementStartDelay
: Configuration
.getElementStartDelay(),
148 poolMaxSize
: Configuration
.getWorkerPoolMaxSize(),
149 poolMinSize
: Configuration
.getWorkerPoolMinSize(),
150 elementsPerWorker
: Configuration
.getChargingStationsPerWorker(),
152 workerChoiceStrategy
: Configuration
.getWorkerPoolStrategy(),
154 messageHandler
: async (msg
: ChargingStationWorkerMessage
) => {
155 console
.log('initWorkerImplementation: messageHandler: ', msg
);
156 if (msg
.id
=== ChargingStationWorkerMessageEvents
.STARTED
) {
157 this.uiWebSocketServer
.chargingStations
.add(msg
.data
.id
as string);
158 console
.log(this.uiWebSocketServer
.chargingStations
);
159 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.STOPPED
) {
160 this.uiWebSocketServer
.chargingStations
.delete(msg
.data
.id
as string);
161 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
) {
162 await this.storage
.storePerformanceStatistics(msg
.data
as unknown
as Statistics
);
169 private async startChargingStation(
171 stationTemplateUrl
: StationTemplateUrl
173 const workerData
: ChargingStationWorkerData
= {
175 templateFile
: path
.join(
176 path
.resolve(__dirname
, '../'),
179 path
.basename(stationTemplateUrl
.file
)
182 await this.workerImplementation
.addElement(workerData
);
183 this.numberOfChargingStations
++;
186 private logPrefix(): string {
187 return Utils
.logPrefix(' Bootstrap |');