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