1 import type { ClusterSettings
} from
'node:cluster'
2 import type { EventEmitterAsyncResource
} from
'node:events'
3 import type { TransferListItem
, WorkerOptions
} from
'node:worker_threads'
5 import type { TaskFunction
} from
'../worker/task-functions.js'
8 WorkerChoiceStrategyOptions
9 } from
'./selection-strategies/selection-strategies-types.js'
21 * Enumeration of pool types.
23 export const PoolTypes
: Readonly
<{
40 export type PoolType
= keyof
typeof PoolTypes
43 * Enumeration of pool events.
45 export const PoolEvents
: Readonly
<{
52 taskError
: 'taskError'
53 backPressure
: 'backPressure'
61 taskError
: 'taskError',
62 backPressure
: 'backPressure'
68 export type PoolEvent
= keyof
typeof PoolEvents
73 export interface PoolInfo
{
74 readonly version
: string
75 readonly type: PoolType
76 readonly worker
: WorkerType
77 readonly started
: boolean
78 readonly ready
: boolean
79 readonly strategy
: WorkerChoiceStrategy
80 readonly strategyRetries
: number
81 readonly minSize
: number
82 readonly maxSize
: number
83 /** Pool utilization. */
84 readonly utilization
?: number
85 /** Pool total worker nodes. */
86 readonly workerNodes
: number
87 /** Pool stealing worker nodes. */
88 readonly stealingWorkerNodes
?: number
89 /** Pool idle worker nodes. */
90 readonly idleWorkerNodes
: number
91 /** Pool busy worker nodes. */
92 readonly busyWorkerNodes
: number
93 readonly executedTasks
: number
94 readonly executingTasks
: number
95 readonly queuedTasks
?: number
96 readonly maxQueuedTasks
?: number
97 readonly backPressure
?: boolean
98 readonly stolenTasks
?: number
99 readonly failedTasks
: number
101 readonly minimum
: number
102 readonly maximum
: number
103 readonly average
?: number
104 readonly median
?: number
106 readonly waitTime
?: {
107 readonly minimum
: number
108 readonly maximum
: number
109 readonly average
?: number
110 readonly median
?: number
115 * Worker node tasks queue options.
117 export interface TasksQueueOptions
{
119 * Maximum tasks queue size per worker node flagging it as back pressured.
121 * @defaultValue (pool maximum size)^2
123 readonly size
?: number
125 * Maximum number of tasks that can be executed concurrently on a worker node.
129 readonly concurrency
?: number
131 * Whether to enable task stealing on idle.
135 readonly taskStealing
?: boolean
137 * Whether to enable tasks stealing under back pressure.
141 readonly tasksStealingOnBackPressure
?: boolean
143 * Queued tasks finished timeout in milliseconds at worker node termination.
147 readonly tasksFinishedTimeout
?: number
151 * Options for a poolifier pool.
153 * @typeParam Worker - Type of worker.
155 export interface PoolOptions
<Worker
extends IWorker
> {
157 * A function that will listen for online event on each worker.
159 * @defaultValue `() => {}`
161 onlineHandler
?: OnlineHandler
<Worker
>
163 * A function that will listen for message event on each worker.
165 * @defaultValue `() => {}`
167 messageHandler
?: MessageHandler
<Worker
>
169 * A function that will listen for error event on each worker.
171 * @defaultValue `() => {}`
173 errorHandler
?: ErrorHandler
<Worker
>
175 * A function that will listen for exit event on each worker.
177 * @defaultValue `() => {}`
179 exitHandler
?: ExitHandler
<Worker
>
181 * Whether to start the minimum number of workers at pool initialization.
185 startWorkers
?: boolean
187 * The worker choice strategy to use in this pool.
189 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
191 workerChoiceStrategy
?: WorkerChoiceStrategy
193 * The worker choice strategy options.
195 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
197 * Restart worker on error.
199 restartWorkerOnError
?: boolean
201 * Pool events integrated with async resource emission.
205 enableEvents
?: boolean
207 * Pool worker node tasks queue.
209 * @defaultValue false
211 enableTasksQueue
?: boolean
213 * Pool worker node tasks queue options.
215 tasksQueueOptions
?: TasksQueueOptions
219 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
221 workerOptions
?: WorkerOptions
223 * Key/value pairs to add to worker process environment.
225 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
227 env
?: Record
<string, unknown
>
231 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
233 settings
?: ClusterSettings
237 * Contract definition for a poolifier pool.
239 * @typeParam Worker - Type of worker which manages this pool.
240 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
241 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
243 export interface IPool
<
244 Worker
extends IWorker
,
251 readonly info
: PoolInfo
257 readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>>
259 * Pool event emitter integrated with async resource.
260 * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
262 * Events that can currently be listened to:
264 * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready. If the pool is dynamic with a minimum number of workers is set to zero, this event is emitted when at least one dynamic worker is ready.
265 * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
266 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
267 * - `'empty'`: Emitted when the pool is dynamic with a minimum number of workers set to zero and the number of workers has reached the minimum size expected.
268 * - `'destroy'`: Emitted when the pool is destroyed.
269 * - `'error'`: Emitted when an uncaught error occurs.
270 * - `'taskError'`: Emitted when an error occurs while executing a task.
271 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= maximum queue size).
273 readonly emitter
?: EventEmitterAsyncResource
275 * Executes the specified function in the worker constructor with the task data input parameter.
277 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
278 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
279 * @param transferList - An optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards.
280 * @returns Promise that will be fulfilled when the task is completed.
285 transferList
?: TransferListItem
[]
286 ) => Promise
<Response
>
288 * Starts the minimum number of workers in this pool.
290 readonly start
: () => void
292 * Terminates all workers in this pool.
294 readonly destroy
: () => Promise
<void>
296 * Whether the specified task function exists in this pool.
298 * @param name - The name of the task function.
299 * @returns `true` if the task function exists, `false` otherwise.
301 readonly hasTaskFunction
: (name
: string) => boolean
303 * Adds a task function to this pool.
304 * If a task function with the same name already exists, it will be overwritten.
306 * @param name - The name of the task function.
307 * @param fn - The task function.
308 * @returns `true` if the task function was added, `false` otherwise.
309 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
310 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
312 readonly addTaskFunction
: (
314 fn
: TaskFunction
<Data
, Response
>
315 ) => Promise
<boolean>
317 * Removes a task function from this pool.
319 * @param name - The name of the task function.
320 * @returns `true` if the task function was removed, `false` otherwise.
322 readonly removeTaskFunction
: (name
: string) => Promise
<boolean>
324 * Lists the names of task function available in this pool.
326 * @returns The names of task function available in this pool.
328 readonly listTaskFunctionNames
: () => string[]
330 * Sets the default task function in this pool.
332 * @param name - The name of the task function.
333 * @returns `true` if the default task function was set, `false` otherwise.
335 readonly setDefaultTaskFunction
: (name
: string) => Promise
<boolean>
337 * Sets the worker choice strategy in this pool.
339 * @param workerChoiceStrategy - The worker choice strategy.
340 * @param workerChoiceStrategyOptions - The worker choice strategy options.
342 readonly setWorkerChoiceStrategy
: (
343 workerChoiceStrategy
: WorkerChoiceStrategy
,
344 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
347 * Sets the worker choice strategy options in this pool.
349 * @param workerChoiceStrategyOptions - The worker choice strategy options.
351 readonly setWorkerChoiceStrategyOptions
: (
352 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
355 * Enables/disables the worker node tasks queue in this pool.
357 * @param enable - Whether to enable or disable the worker node tasks queue.
358 * @param tasksQueueOptions - The worker node tasks queue options.
360 readonly enableTasksQueue
: (
362 tasksQueueOptions
?: TasksQueueOptions
365 * Sets the worker node tasks queue options in this pool.
367 * @param tasksQueueOptions - The worker node tasks queue options.
369 readonly setTasksQueueOptions
: (tasksQueueOptions
: TasksQueueOptions
) => void