Fix worker startup and cleanup some attributes in Wrk class.
[e-mobility-charging-stations-simulator.git] / src / start.ts
1 import Configuration from './utils/Configuration';
2 import Constants from './utils/Constants';
3 import Utils from './utils/Utils';
4 import WorkerData from './types/WorkerData';
5 import Wrk from './charging-station/Worker';
6
7 class Bootstrap {
8 static async start() {
9 try {
10 let numStationsTotal = 0;
11 let numConcurrentWorkers = 0;
12 const chargingStationsPerWorker = Configuration.getChargingStationsPerWorker();
13 let chargingStationsPerWorkerCounter = 0;
14 let worker: Wrk;
15 // Start each ChargingStation object in a worker thread
16 if (Configuration.getStationTemplateURLs()) {
17 for (const stationURL of Configuration.getStationTemplateURLs()) {
18 try {
19 const nbStations = stationURL.numberOfStations ? stationURL.numberOfStations : 0;
20 numStationsTotal += nbStations;
21 for (let index = 1; index <= nbStations; index++) {
22 const workerData = {
23 index,
24 templateFile: stationURL.file
25 } as WorkerData;
26 if (Configuration.useWorkerPool()) {
27 worker = new Wrk('./dist/charging-station/StationWorker.js', workerData);
28 worker.start().catch(() => { });
29 numConcurrentWorkers = Configuration.getWorkerPoolSize();
30 } else if (!Configuration.useWorkerPool() && (chargingStationsPerWorkerCounter === 0 || chargingStationsPerWorkerCounter === chargingStationsPerWorker)) {
31 // Start new Wrk with one charging station
32 worker = new Wrk('./dist/charging-station/StationWorker.js', workerData);
33 worker.start().catch(() => { });
34 numConcurrentWorkers++;
35 chargingStationsPerWorkerCounter = 1;
36 // Start Wrk sequentially to optimize memory at start time
37 await Utils.sleep(Constants.START_WORKER_DELAY);
38 } else if (!Configuration.useWorkerPool()) {
39 // Add charging station to existing Wrk
40 worker.addWorkerElement(workerData);
41 chargingStationsPerWorkerCounter++;
42 }
43 }
44 } catch (error) {
45 // eslint-disable-next-line no-console
46 console.log('Charging station start with template file ' + stationURL.file + ' error ' + JSON.stringify(error, null, ' '));
47 }
48 }
49 } else {
50 console.log('No stationTemplateURLs defined in configuration, exiting');
51 }
52 if (numStationsTotal === 0) {
53 console.log('No charging station template enabled in configuration, exiting');
54 } else {
55 console.log('Charging station simulator started with ' + numStationsTotal.toString() + ' charging station(s) of ' + numConcurrentWorkers.toString() + ' concurrently running');
56 }
57 } catch (error) {
58 // eslint-disable-next-line no-console
59 console.log('Bootstrap start error ' + JSON.stringify(error, null, ' '));
60 }
61 }
62 }
63
64 Bootstrap.start().catch(
65 (error) => {
66 console.error(error);
67 }
68 );