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