1 import { AsyncResource
} from
'node:async_hooks'
2 import type { Worker
} from
'node:cluster'
3 import type { MessagePort
} from
'node:worker_threads'
4 import type { MessageValue
} from
'../utility-types'
5 import { EMPTY_FUNCTION
} from
'../utils'
6 import type { KillBehavior
, WorkerOptions
} from
'./worker-options'
7 import { KillBehaviors
} from
'./worker-options'
9 const DEFAULT_MAX_INACTIVE_TIME
= 60000
10 const DEFAULT_KILL_BEHAVIOR
: KillBehavior
= KillBehaviors
.SOFT
13 * Base class that implements some shared logic for all poolifier workers.
15 * @typeParam MainWorker - Type of main worker.
16 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
17 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
19 export abstract class AbstractWorker
<
20 MainWorker
extends Worker
| MessagePort
,
23 > extends AsyncResource
{
25 * Timestamp of the last task processed by this worker.
27 protected lastTaskTimestamp
!: number
29 * Handler id of the `aliveInterval` worker alive check.
31 protected readonly aliveInterval
?: NodeJS
.Timeout
33 * Constructs a new poolifier worker.
35 * @param type - The type of async event.
36 * @param isMain - Whether this is the main worker or not.
37 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
38 * @param mainWorker - Reference to main worker.
39 * @param opts - Options for the worker.
43 protected readonly isMain
: boolean,
44 fn
: (data
: Data
) => Response
| Promise
<Response
>,
45 protected mainWorker
: MainWorker
| undefined | null,
46 protected readonly opts
: WorkerOptions
= {
48 * The kill behavior option on this worker or its default value.
50 killBehavior
: DEFAULT_KILL_BEHAVIOR
,
52 * The maximum time to keep this worker alive while idle.
53 * The pool automatically checks and terminates this worker when the time expires.
55 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
59 this.checkWorkerOptions(this.opts
)
60 this.checkFunctionInput(fn
)
62 this.lastTaskTimestamp
= performance
.now()
63 this.aliveInterval
= setInterval(
64 this.checkAlive
.bind(this),
65 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
67 this.checkAlive
.bind(this)()
72 (message
: MessageValue
<Data
, MainWorker
>) => {
73 this.messageListener(message
, fn
)
79 * Worker message listener.
81 * @param message - Message received.
82 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
84 protected messageListener (
85 message
: MessageValue
<Data
, MainWorker
>,
86 fn
: (data
: Data
) => Response
| Promise
<Response
>
88 if (message
.id
!= null && message
.data
!= null) {
89 // Task message received
90 if (this.opts
.async === true) {
91 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, message
)
93 this.runInAsyncScope(this.run
.bind(this), this, fn
, message
)
95 } else if (message
.parent != null) {
96 // Main worker reference message received
97 this.mainWorker
= message
.parent
98 } else if (message
.kill
!= null) {
99 // Kill message received
100 this.aliveInterval
!= null && clearInterval(this.aliveInterval
)
105 private checkWorkerOptions (opts
: WorkerOptions
): void {
106 this.opts
.killBehavior
= opts
.killBehavior
?? DEFAULT_KILL_BEHAVIOR
107 this.opts
.maxInactiveTime
=
108 opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
109 this.opts
.async = opts
.async ?? false
113 * Checks if the `fn` parameter is passed to the constructor.
115 * @param fn - The function that should be defined.
117 private checkFunctionInput (
118 fn
: (data
: Data
) => Response
| Promise
<Response
>
120 if (fn
== null) throw new Error('fn parameter is mandatory')
121 if (typeof fn
!== 'function') {
122 throw new TypeError('fn parameter is not a function')
124 if (fn
.constructor
.name
=== 'AsyncFunction' && this.opts
.async === false) {
126 'fn parameter is an async function, please set the async option to true'
132 * Returns the main worker.
134 * @returns Reference to the main worker.
136 protected getMainWorker (): MainWorker
{
137 if (this.mainWorker
== null) {
138 throw new Error('Main worker was not set')
140 return this.mainWorker
144 * Sends a message to the main worker.
146 * @param message - The response message.
148 protected abstract sendToMainWorker (message
: MessageValue
<Response
>): void
151 * Checks if the worker should be terminated, because its living too long.
153 protected checkAlive (): void {
155 performance
.now() - this.lastTaskTimestamp
>
156 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
158 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
163 * Handles an error and convert it to a string so it can be sent back to the main worker.
165 * @param e - The error raised by the worker.
166 * @returns Message of the error.
168 protected handleError (e
: Error | string): string {
173 * Runs the given function synchronously.
175 * @param fn - Function that will be executed.
176 * @param message - Input data for the given function.
179 fn
: (data
?: Data
) => Response
,
180 message
: MessageValue
<Data
>
183 const startTimestamp
= performance
.now()
184 const res
= fn(message
.data
)
185 const runTime
= performance
.now() - startTimestamp
186 this.sendToMainWorker({
192 const err
= this.handleError(e
as Error)
193 this.sendToMainWorker({ error
: err
, id
: message
.id
})
195 !this.isMain
&& (this.lastTaskTimestamp
= performance
.now())
200 * Runs the given function asynchronously.
202 * @param fn - Function that will be executed.
203 * @param message - Input data for the given function.
206 fn
: (data
?: Data
) => Promise
<Response
>,
207 message
: MessageValue
<Data
>
209 const startTimestamp
= performance
.now()
212 const runTime
= performance
.now() - startTimestamp
213 this.sendToMainWorker({
221 const err
= this.handleError(e
as Error)
222 this.sendToMainWorker({ error
: err
, id
: message
.id
})
225 !this.isMain
&& (this.lastTaskTimestamp
= performance
.now())
227 .catch(EMPTY_FUNCTION
)