1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import path from
'path';
4 import { fileURLToPath
} from
'url';
5 import { type Worker
, isMainThread
} from
'worker_threads';
7 import chalk from
'chalk';
9 import { ChargingStationUtils
} from
'./ChargingStationUtils';
10 import type { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
11 import UIServerFactory from
'./ui-server/UIServerFactory';
12 import { version
} from
'../../package.json';
13 import BaseError from
'../exception/BaseError';
14 import type { Storage
} from
'../performance/storage/Storage';
15 import { StorageFactory
} from
'../performance/storage/StorageFactory';
17 type ChargingStationData
,
18 type ChargingStationWorkerData
,
19 type ChargingStationWorkerMessage
,
20 type ChargingStationWorkerMessageData
,
21 ChargingStationWorkerMessageEvents
,
22 } from
'../types/ChargingStationWorker';
23 import type { StationTemplateUrl
} from
'../types/ConfigurationData';
24 import type { Statistics
} from
'../types/Statistics';
25 import type { MessageHandler
} from
'../types/Worker';
26 import Configuration from
'../utils/Configuration';
27 import logger from
'../utils/Logger';
28 import Utils from
'../utils/Utils';
29 import type WorkerAbstract from
'../worker/WorkerAbstract';
30 import WorkerFactory from
'../worker/WorkerFactory';
32 const moduleName
= 'Bootstrap';
35 missingChargingStationsConfiguration
= 1,
36 noChargingStationTemplates
= 2,
39 export class Bootstrap
{
40 private static instance
: Bootstrap
| null = null;
41 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null;
42 private readonly uiServer
!: AbstractUIServer
;
43 private readonly storage
!: Storage
;
44 private numberOfChargingStationTemplates
!: number;
45 private numberOfChargingStations
!: number;
46 private numberOfStartedChargingStations
!: number;
47 private readonly version
: string = version
;
48 private started
: boolean;
49 private readonly workerScript
: string;
51 private constructor() {
53 this.workerImplementation
= null;
54 this.workerScript
= path
.join(
55 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
57 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
60 Configuration
.getUIServer().enabled
=== true &&
61 (this.uiServer
= UIServerFactory
.getUIServerImplementation(Configuration
.getUIServer()));
62 Configuration
.getPerformanceStorage().enabled
=== true &&
63 (this.storage
= StorageFactory
.getStorage(
64 Configuration
.getPerformanceStorage().type,
65 Configuration
.getPerformanceStorage().uri
,
68 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
71 public static getInstance(): Bootstrap
{
72 if (Bootstrap
.instance
=== null) {
73 Bootstrap
.instance
= new Bootstrap();
75 return Bootstrap
.instance
;
78 public async start(): Promise
<void> {
79 if (isMainThread
&& this.started
=== false) {
81 // Enable unconditionally for now
82 this.logUnhandledRejection();
83 this.logUncaughtException();
85 await this.storage
?.open();
86 await this.workerImplementation
?.start();
87 this.uiServer
?.start();
88 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
89 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
90 // Start ChargingStation object in worker thread
91 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
92 for (const stationTemplateUrl
of stationTemplateUrls
) {
94 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
95 for (let index
= 1; index
<= nbStations
; index
++) {
96 await this.startChargingStation(index
, stationTemplateUrl
);
101 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
109 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
111 process
.exit(exitCodes
.missingChargingStationsConfiguration
);
113 if (this.numberOfChargingStations
=== 0) {
115 chalk
.yellow('No charging station template enabled in configuration, exiting')
117 process
.exit(exitCodes
.noChargingStationTemplates
);
121 `Charging stations simulator ${
123 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
124 ChargingStationUtils.workerDynamicPoolInUse()
125 ? `${Configuration.getWorker().poolMinSize?.toString()}
/`
127 }${this.workerImplementation?.size}${
128 ChargingStationUtils.workerPoolInUse()
129 ? `/${Configuration.getWorker().poolMaxSize?.toString()}
`
131 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
132 this.workerImplementation?.maxElementsPerWorker
133 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging
station(s
) per worker
)`
141 console
.error(chalk
.red('Bootstrap start error: '), error
);
144 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
148 public async stop(): Promise
<void> {
149 if (isMainThread
&& this.started
=== true) {
150 await this.workerImplementation
?.stop();
151 this.workerImplementation
= null;
152 this.uiServer
?.stop();
153 await this.storage
?.close();
154 this.started
= false;
156 console
.error(chalk
.red('Cannot stop a not started charging stations simulator'));
160 public async restart(): Promise
<void> {
166 private initializeWorkerImplementation(): void {
167 this.workerImplementation
=== null &&
168 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
170 Configuration
.getWorker().processType
,
172 workerStartDelay
: Configuration
.getWorker().startDelay
,
173 elementStartDelay
: Configuration
.getWorker().elementStartDelay
,
174 poolMaxSize
: Configuration
.getWorker().poolMaxSize
,
175 poolMinSize
: Configuration
.getWorker().poolMinSize
,
176 elementsPerWorker
: Configuration
.getWorker().elementsPerWorker
,
178 workerChoiceStrategy
: Configuration
.getWorker().poolStrategy
,
180 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
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
;
228 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
229 data.stationInfo.chargingStationId
230 } (hashId: ${data.stationInfo.hashId}) started (${
231 this.numberOfStartedChargingStations
232 } started from ${this.numberOfChargingStations})`
236 private workerEventStopped
= (data
: ChargingStationData
) => {
237 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
238 --this.numberOfStartedChargingStations
;
240 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
241 data.stationInfo.chargingStationId
242 } (hashId: ${data.stationInfo.hashId}) stopped (${
243 this.numberOfStartedChargingStations
244 } started from ${this.numberOfChargingStations})`
248 private workerEventUpdated
= (data
: ChargingStationData
) => {
249 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
);
252 private workerEventPerformanceStatistics
= (data
: Statistics
) => {
253 this.storage
.storePerformanceStatistics(data
) as void;
256 private initialize() {
257 this.numberOfChargingStationTemplates
= 0;
258 this.numberOfChargingStations
= 0;
259 this.numberOfStartedChargingStations
= 0;
260 this.initializeWorkerImplementation();
263 private logUncaughtException(): void {
264 process
.on('uncaughtException', (error
: Error) => {
265 console
.error(chalk
.red('Uncaught exception: '), error
);
269 private logUnhandledRejection(): void {
270 process
.on('unhandledRejection', (reason
: unknown
) => {
271 console
.error(chalk
.red('Unhandled rejection: '), reason
);
275 private async startChargingStation(
277 stationTemplateUrl
: StationTemplateUrl
279 const workerData
: ChargingStationWorkerData
= {
281 templateFile
: path
.join(
282 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
285 stationTemplateUrl
.file
288 await this.workerImplementation
.addElement(workerData
);
289 ++this.numberOfChargingStations
;
292 private logPrefix(): string {
293 return Utils
.logPrefix(' Bootstrap |');