Simplify DC current output type handling.
[e-mobility-charging-stations-simulator.git] / src / charging-station / Worker.js
CommitLineData
3f40bc9c
JB
1import Configuration from '../utils/Configuration.js';
2import EventEmitter from 'events';
3import Pool from 'worker-threads-pool';
4import {Worker} from 'worker_threads';
7dde0b73 5
3f40bc9c 6export default class Wrk {
7dde0b73
JB
7 /**
8 * Create a new `Wrk`.
9 *
10 * @param {String} workerScript
11 * @param {Object} workerData
6798437b 12 * @param {Number} numConcurrentWorkers
7dde0b73 13 */
6798437b
JB
14 constructor(workerScript, workerData, numConcurrentWorkers) {
15 this._workerData = workerData;
16 this._workerScript = workerScript;
17 this._numConcurrentWorkers = numConcurrentWorkers;
7dde0b73
JB
18 if (Configuration.useWorkerPool()) {
19 this._pool = new Pool({max: Configuration.getWorkerPoolSize()});
20 }
6798437b
JB
21 }
22
23 /**
24 * @param {Number} numConcurrentWorkers
25 * @private
26 */
6798437b
JB
27 set _numConcurrentWorkers(numConcurrentWorkers) {
28 if (numConcurrentWorkers > 10) {
29 EventEmitter.defaultMaxListeners = numConcurrentWorkers + 1;
30 }
31 this._concurrentWorkers = numConcurrentWorkers;
32 }
33
6798437b
JB
34 get _numConcurrentWorkers() {
35 return this._concurrentWorkers;
7dde0b73
JB
36 }
37
38 /**
39 *
40 * @return {Promise}
41 * @private
42 */
43 _startWorkerWithPool() {
44 return new Promise((resolve, reject) => {
45 this._pool.acquire(this._workerScript, {workerData: this._workerData}, (err, worker) => {
46 if (err) {
47 return reject(err);
48 }
49 worker.once('message', resolve);
50 worker.once('error', reject);
51 });
52 });
53 }
54
55 /**
56 *
57 * @return {Promise}
58 * @private
59 */
60 _startWorker() {
61 return new Promise((resolve, reject) => {
62 const worker = new Worker(this._workerScript, {workerData: this._workerData});
63 worker.on('message', resolve);
64 worker.on('error', reject);
65 worker.on('exit', (code) => {
66 if (code !== 0) {
67 reject(new Error(`Worker stopped with exit code ${code}`));
68 }
69 });
70 });
71 }
72
73 /**
74 *
75 * @return {Promise}
76 * @public
77 */
78 start() {
79 if (Configuration.useWorkerPool()) {
80 return this._startWorkerWithPool();
81 }
82 return this._startWorker();
83 }
84}