Added prettier standard to support prettier and use it in combination with standard
[poolifier.git] / lib / workers.js
1 'use strict'
2 const { isMainThread, parentPort } = require('worker_threads')
3 const { AsyncResource } = require('async_hooks')
4
5 /**
6 * An example worker that will be always alive, you just need to extend this class if you want a static pool.<br>
7 * When this worker is inactive for more than 1 minute, it will send this info to the main thread,<br>
8 * if you are using DynamicThreadPool, the workers created after will be killed, the min num of thread will be guaranteed
9 * @author Alessandro Pio Ardizio
10 * @since 0.0.1
11 */
12 class ThreadWorker extends AsyncResource {
13 constructor (fn, opts) {
14 super('worker-thread-pool:pioardi')
15 this.opts = opts || {}
16 this.maxInactiveTime = this.opts.maxInactiveTime || 1000 * 60
17 this.async = !!this.opts.async
18 this.lastTask = Date.now()
19 if (!fn) throw new Error('Fn parameter is mandatory')
20 // keep the worker active
21 if (!isMainThread) {
22 this.interval = setInterval(
23 this._checkAlive.bind(this),
24 this.maxInactiveTime / 2
25 )
26 this._checkAlive.bind(this)()
27 }
28 parentPort.on('message', value => {
29 if (value && value.data && value._id) {
30 // here you will receive messages
31 // console.log('This is the main thread ' + isMainThread)
32 if (this.async) {
33 this.runInAsyncScope(this._runAsync.bind(this), this, fn, value)
34 } else {
35 this.runInAsyncScope(this._run.bind(this), this, fn, value)
36 }
37 } else if (value.parent) {
38 // save the port to communicate with the main thread
39 // this will be received once
40 this.parent = value.parent
41 } else if (value.kill) {
42 // here is time to kill this thread, just clearing the interval
43 clearInterval(this.interval)
44 this.emitDestroy()
45 }
46 })
47 }
48
49 _checkAlive () {
50 if (Date.now() - this.lastTask > this.maxInactiveTime) {
51 this.parent.postMessage({ kill: 1 })
52 }
53 }
54
55 _run (fn, value) {
56 try {
57 const res = fn(value.data)
58 this.parent.postMessage({ data: res, _id: value._id })
59 this.lastTask = Date.now()
60 } catch (e) {
61 this.parent.postMessage({ error: e, _id: value._id })
62 this.lastTask = Date.now()
63 }
64 }
65
66 _runAsync (fn, value) {
67 fn(value.data)
68 .then(res => {
69 this.parent.postMessage({ data: res, _id: value._id })
70 this.lastTask = Date.now()
71 })
72 .catch(e => {
73 this.parent.postMessage({ error: e, _id: value._id })
74 this.lastTask = Date.now()
75 })
76 }
77 }
78
79 module.exports.ThreadWorker = ThreadWorker