1 import { AsyncResource
} from
'async_hooks'
2 import type { Worker
} from
'cluster'
3 import type { MessagePort
} from
'worker_threads'
4 import type { MessageValue
} from
'../utility-types'
5 import type { WorkerOptions
} from
'./worker-options'
6 import { killBehaviorEnumeration
} from
'./worker-options'
8 const defaultMaxInactiveTime
= 1000 * 60
9 const defaultKillBehavior
= killBehaviorEnumeration
.SOFT
12 * Base class containing some shared logic for all poolifier workers.
14 * @template MainWorker Type of main worker.
15 * @template Data Type of data this worker receives from pool's execution.
16 * @template Response Type of response the worker sends back to the main worker.
18 export abstract class AbstractWorker
<
19 MainWorker
extends Worker
| MessagePort
,
22 > extends AsyncResource
{
24 * The maximum time to keep this worker alive while idle. The pool automatically checks and terminates this worker when the time expires.
26 protected readonly maxInactiveTime
: number
28 * The kill behavior set as option on the Worker constructor or a default value.
30 protected readonly killBehavior
: 'HARD' | 'SOFT'
32 * Whether the worker is working asynchronously or not.
34 protected readonly async: boolean
36 * Timestamp of the last task processed by this worker.
38 protected lastTask
: number
40 * Handler ID of the `interval` alive check.
42 protected readonly interval
?: NodeJS
.Timeout
45 * Constructs a new poolifier worker.
47 * @param type The type of async event.
48 * @param isMain Whether this is the main worker or not.
49 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
50 * @param mainWorker Reference to main worker.
51 * @param opts Options for the worker.
56 fn
: (data
: Data
) => Response
,
57 protected mainWorker
?: MainWorker
| null,
58 public readonly opts
: WorkerOptions
= {
59 killBehavior
: defaultKillBehavior
,
60 maxInactiveTime
: defaultMaxInactiveTime
64 this.killBehavior
= this.opts
.killBehavior
?? defaultKillBehavior
65 this.maxInactiveTime
= this.opts
.maxInactiveTime
?? defaultMaxInactiveTime
66 this.async = !!this.opts
.async
67 this.lastTask
= Date.now()
68 if (!fn
) throw new Error('fn parameter is mandatory')
69 // Keep the worker active
71 this.interval
= setInterval(
72 this.checkAlive
.bind(this),
73 this.maxInactiveTime
/ 2
75 this.checkAlive
.bind(this)()
78 this.mainWorker
?.on('message', (value
: MessageValue
<Data
, MainWorker
>) => {
79 if (value
?.data
&& value
.id
) {
80 // Here you will receive messages
82 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, value
)
84 this.runInAsyncScope(this.run
.bind(this), this, fn
, value
)
86 } else if (value
.parent) {
87 // Save a reference of the main worker to communicate with it
88 // This will be received once
89 this.mainWorker
= value
.parent
90 } else if (value
.kill
) {
91 // Here is time to kill this worker, just clearing the interval
92 if (this.interval
) clearInterval(this.interval
)
99 * Returns the main worker.
101 * @returns Reference to the main worker.
103 protected getMainWorker (): MainWorker
{
104 if (!this.mainWorker
) {
105 throw new Error('Main worker was not set')
107 return this.mainWorker
111 * Send a message to the main worker.
113 * @param message The response message.
115 protected abstract sendToMainWorker (message
: MessageValue
<Response
>): void
118 * Check to see if the worker should be terminated, because its living too long.
120 protected checkAlive (): void {
121 if (Date.now() - this.lastTask
> this.maxInactiveTime
) {
122 this.sendToMainWorker({ kill
: this.killBehavior
})
127 * Handle an error and convert it to a string so it can be sent back to the main worker.
129 * @param e The error raised by the worker.
130 * @returns Message of the error.
132 protected handleError (e
: Error | string): string {
133 return (e
as unknown
) as string
137 * Run the given function synchronously.
139 * @param fn Function that will be executed.
140 * @param value Input data for the given function.
143 fn
: (data
?: Data
) => Response
,
144 value
: MessageValue
<Data
>
147 const res
= fn(value
.data
)
148 this.sendToMainWorker({ data
: res
, id
: value
.id
})
149 this.lastTask
= Date.now()
151 const err
= this.handleError(e
)
152 this.sendToMainWorker({ error
: err
, id
: value
.id
})
153 this.lastTask
= Date.now()
158 * Run the given function asynchronously.
160 * @param fn Function that will be executed.
161 * @param value Input data for the given function.
164 fn
: (data
?: Data
) => Promise
<Response
>,
165 value
: MessageValue
<Data
>
169 this.sendToMainWorker({ data
: res
, id
: value
.id
})
170 this.lastTask
= Date.now()
174 const err
= this.handleError(e
)
175 this.sendToMainWorker({ error
: err
, id
: value
.id
})
176 this.lastTask
= Date.now()