1 import { AsyncResource
} from
'node:async_hooks'
2 import type { Worker
} from
'node:cluster'
3 import type { MessagePort
} from
'node:worker_threads'
9 } from
'../utility-types'
10 import { EMPTY_FUNCTION
} from
'../utils'
11 import type { KillBehavior
, WorkerOptions
} from
'./worker-options'
12 import { KillBehaviors
} from
'./worker-options'
14 const DEFAULT_MAX_INACTIVE_TIME
= 60000
15 const DEFAULT_KILL_BEHAVIOR
: KillBehavior
= KillBehaviors
.SOFT
18 * Base class that implements some shared logic for all poolifier workers.
20 * @typeParam MainWorker - Type of main worker.
21 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
22 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
24 export abstract class AbstractWorker
<
25 MainWorker
extends Worker
| MessagePort
,
28 > extends AsyncResource
{
30 * Timestamp of the last task processed by this worker.
32 protected lastTaskTimestamp
!: number
34 * Handler id of the `aliveInterval` worker alive check.
36 protected readonly aliveInterval
?: NodeJS
.Timeout
38 * Constructs a new poolifier worker.
40 * @param type - The type of async event.
41 * @param isMain - Whether this is the main worker or not.
42 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
43 * @param mainWorker - Reference to main worker.
44 * @param opts - Options for the worker.
48 protected readonly isMain
: boolean,
49 fn
: WorkerFunction
<Data
, Response
>,
50 protected mainWorker
: MainWorker
| undefined | null,
51 protected readonly opts
: WorkerOptions
= {
53 * The kill behavior option on this worker or its default value.
55 killBehavior
: DEFAULT_KILL_BEHAVIOR
,
57 * The maximum time to keep this worker alive while idle.
58 * The pool automatically checks and terminates this worker when the time expires.
60 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
64 this.checkWorkerOptions(this.opts
)
65 this.checkFunctionInput(fn
)
67 this.lastTaskTimestamp
= performance
.now()
68 this.aliveInterval
= setInterval(
69 this.checkAlive
.bind(this),
70 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
72 this.checkAlive
.bind(this)()
77 (message
: MessageValue
<Data
, MainWorker
>) => {
78 this.messageListener(message
, fn
)
83 private checkWorkerOptions (opts
: WorkerOptions
): void {
84 this.opts
.killBehavior
= opts
.killBehavior
?? DEFAULT_KILL_BEHAVIOR
85 this.opts
.maxInactiveTime
=
86 opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
87 this.opts
.async = opts
.async ?? false
91 * Checks if the `fn` parameter is passed to the constructor.
93 * @param fn - The function that should be defined.
95 private checkFunctionInput (fn
: WorkerFunction
<Data
, Response
>): void {
96 if (fn
== null) throw new Error('fn parameter is mandatory')
97 if (typeof fn
!== 'function') {
98 throw new TypeError('fn parameter is not a function')
100 if (fn
.constructor
.name
=== 'AsyncFunction' && this.opts
.async === false) {
102 'fn parameter is an async function, please set the async option to true'
108 * Worker message listener.
110 * @param message - Message received.
111 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
113 protected messageListener (
114 message
: MessageValue
<Data
, MainWorker
>,
115 fn
: WorkerFunction
<Data
, Response
>
117 if (message
.id
!= null && message
.data
!= null) {
118 // Task message received
119 if (this.opts
.async === true) {
120 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, message
)
122 this.runInAsyncScope(this.run
.bind(this), this, fn
, message
)
124 } else if (message
.parent != null) {
125 // Main worker reference message received
126 this.mainWorker
= message
.parent
127 } else if (message
.kill
!= null) {
128 // Kill message received
129 this.aliveInterval
!= null && clearInterval(this.aliveInterval
)
135 * Returns the main worker.
137 * @returns Reference to the main worker.
139 protected getMainWorker (): MainWorker
{
140 if (this.mainWorker
== null) {
141 throw new Error('Main worker was not set')
143 return this.mainWorker
147 * Sends a message to the main worker.
149 * @param message - The response message.
151 protected abstract sendToMainWorker (message
: MessageValue
<Response
>): void
154 * Checks if the worker should be terminated, because its living too long.
156 protected checkAlive (): void {
158 performance
.now() - this.lastTaskTimestamp
>
159 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
161 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
166 * Handles an error and convert it to a string so it can be sent back to the main worker.
168 * @param e - The error raised by the worker.
169 * @returns Message of the error.
171 protected handleError (e
: Error | string): string {
176 * Runs the given function synchronously.
178 * @param fn - Function that will be executed.
179 * @param message - Input data for the given function.
182 fn
: WorkerSyncFunction
<Data
, Response
>,
183 message
: MessageValue
<Data
>
186 const startTimestamp
= performance
.now()
187 const res
= fn(message
.data
)
188 const runTime
= performance
.now() - startTimestamp
189 this.sendToMainWorker({
195 const err
= this.handleError(e
as Error)
196 this.sendToMainWorker({ error
: err
, id
: message
.id
})
198 !this.isMain
&& (this.lastTaskTimestamp
= performance
.now())
203 * Runs the given function asynchronously.
205 * @param fn - Function that will be executed.
206 * @param message - Input data for the given function.
209 fn
: WorkerAsyncFunction
<Data
, Response
>,
210 message
: MessageValue
<Data
>
212 const startTimestamp
= performance
.now()
215 const runTime
= performance
.now() - startTimestamp
216 this.sendToMainWorker({
224 const err
= this.handleError(e
as Error)
225 this.sendToMainWorker({ error
: err
, id
: message
.id
})
228 !this.isMain
&& (this.lastTaskTimestamp
= performance
.now())
230 .catch(EMPTY_FUNCTION
)