Use generics for incoming message error handling
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
2a370053 1import { ChargingStationWorkerData, WorkerMessage, WorkerMessageEvents } from '../types/Worker';
81797102 2
ded13d97 3import Configuration from '../utils/Configuration';
a6b3c6c3
JB
4import { Storage } from '../performance/storage/Storage';
5import { StorageFactory } from '../performance/storage/StorageFactory';
ded13d97 6import Utils from '../utils/Utils';
fd1fdf1b 7import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 8import WorkerFactory from '../worker/WorkerFactory';
8eac9a09 9import chalk from 'chalk';
ded13d97 10import { isMainThread } from 'worker_threads';
bf1866b2 11import path from 'path';
84e52c2c 12import { version } from '../../package.json';
ded13d97
JB
13
14export default class Bootstrap {
535aaa27
JB
15 private static instance: Bootstrap | null = null;
16 private static workerImplementation: WorkerAbstract | null = null;
81797102 17 private static storage: Storage;
aef1b33a 18 private version: string = version;
eb87fe87 19 private started: boolean;
ded13d97 20 private workerScript: string;
ded13d97
JB
21
22 private constructor() {
eb87fe87 23 this.started = false;
07f35004 24 this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js');
8df3f0a9 25 this.initWorkerImplementation();
81797102 26 Bootstrap.storage = StorageFactory.getStorage(Configuration.getPerformanceStorage().type, Configuration.getPerformanceStorage().URI, this.logPrefix());
7874b0b1 27 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
28 }
29
30 public static getInstance(): Bootstrap {
31 if (!Bootstrap.instance) {
32 Bootstrap.instance = new Bootstrap();
33 }
34 return Bootstrap.instance;
35 }
36
37 public async start(): Promise<void> {
eb87fe87 38 if (isMainThread && !this.started) {
ded13d97
JB
39 try {
40 let numStationsTotal = 0;
2a370053 41 await Bootstrap.storage.open();
535aaa27 42 await Bootstrap.workerImplementation.start();
ded13d97
JB
43 // Start ChargingStation object in worker thread
44 if (Configuration.getStationTemplateURLs()) {
45 for (const stationURL of Configuration.getStationTemplateURLs()) {
46 try {
47 const nbStations = stationURL.numberOfStations ? stationURL.numberOfStations : 0;
48 for (let index = 1; index <= nbStations; index++) {
07f35004 49 const workerData: ChargingStationWorkerData = {
ded13d97 50 index,
bf1866b2 51 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationURL.file))
ded13d97 52 };
535aaa27 53 await Bootstrap.workerImplementation.addElement(workerData);
ded13d97
JB
54 numStationsTotal++;
55 }
56 } catch (error) {
8eac9a09 57 console.error(chalk.red('Charging station start with template file ' + stationURL.file + ' error '), error);
ded13d97
JB
58 }
59 }
60 } else {
8eac9a09 61 console.warn(chalk.yellow('No stationTemplateURLs defined in configuration, exiting'));
ded13d97
JB
62 }
63 if (numStationsTotal === 0) {
8eac9a09 64 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
ded13d97 65 } else {
8eac9a09 66 console.log(chalk.green(`Charging station simulator ${this.version} started with ${numStationsTotal.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${Bootstrap.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${Bootstrap.workerImplementation.maxElementsPerWorker ? ` (${Bootstrap.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`));
ded13d97 67 }
eb87fe87 68 this.started = true;
ded13d97 69 } catch (error) {
8eac9a09 70 console.error(chalk.red('Bootstrap start error '), error);
ded13d97
JB
71 }
72 }
73 }
74
75 public async stop(): Promise<void> {
eb87fe87 76 if (isMainThread && this.started) {
535aaa27 77 await Bootstrap.workerImplementation.stop();
2a370053 78 await Bootstrap.storage.close();
ded13d97 79 }
eb87fe87 80 this.started = false;
ded13d97
JB
81 }
82
83 public async restart(): Promise<void> {
84 await this.stop();
535aaa27 85 this.initWorkerImplementation();
ded13d97
JB
86 await this.start();
87 }
88
2a370053 89 private initWorkerImplementation(): void {
07f35004 90 Bootstrap.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
8df3f0a9
JB
91 {
92 startDelay: Configuration.getWorkerStartDelay(),
93 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
94 poolMinSize: Configuration.getWorkerPoolMinSize(),
95 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
96 poolOptions: {
97 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
ffd71f2c
JB
98 },
99 messageHandler: async (msg: WorkerMessage) => {
100 if (msg.id === WorkerMessageEvents.PERFORMANCE_STATISTICS) {
101 await Bootstrap.storage.storePerformanceStatistics(msg.data);
102 }
81797102 103 }
535aaa27 104 });
ded13d97 105 }
81797102
JB
106
107 private logPrefix(): string {
689dca78 108 return Utils.logPrefix(' Bootstrap |');
81797102 109 }
ded13d97 110}