Initial commit
[e-mobility-charging-stations-simulator.git] / src / charging-station / Worker.js
1 const Configuration = require('../utils/Configuration');
2 const {Worker} = require('worker_threads');
3 const Pool = require('worker-threads-pool');
4
5 class Wrk {
6 /**
7 * Create a new `Wrk`.
8 *
9 * @param {String} workerScript
10 * @param {Object} workerData
11 */
12 constructor(workerScript, workerData) {
13 if (Configuration.useWorkerPool()) {
14 this._pool = new Pool({max: Configuration.getWorkerPoolSize()});
15 }
16 this._workerData = workerData;
17 this._workerScript = workerScript;
18 }
19
20 /**
21 *
22 * @return {Promise}
23 * @private
24 */
25 _startWorkerWithPool() {
26 return new Promise((resolve, reject) => {
27 this._pool.acquire(this._workerScript, {workerData: this._workerData}, (err, worker) => {
28 if (err) {
29 return reject(err);
30 }
31 worker.once('message', resolve);
32 worker.once('error', reject);
33 });
34 });
35 }
36
37 /**
38 *
39 * @return {Promise}
40 * @private
41 */
42 _startWorker() {
43 return new Promise((resolve, reject) => {
44 const worker = new Worker(this._workerScript, {workerData: this._workerData});
45 worker.on('message', resolve);
46 worker.on('error', reject);
47 worker.on('exit', (code) => {
48 if (code !== 0) {
49 reject(new Error(`Worker stopped with exit code ${code}`));
50 }
51 });
52 });
53 }
54
55 /**
56 *
57 * @return {Promise}
58 * @public
59 */
60 start() {
61 if (Configuration.useWorkerPool()) {
62 return this._startWorkerWithPool();
63 }
64 return this._startWorker();
65 }
66 }
67
68 module.exports = Wrk;