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 { TaskFunctionProperties
} from
'../utility-types.js'
6 import type { TaskFunction
} from
'../worker/task-functions.js'
9 WorkerChoiceStrategyOptions
10 } from
'./selection-strategies/selection-strategies-types.js'
22 * Enumeration of pool types.
24 export const PoolTypes
: Readonly
<{
41 export type PoolType
= keyof
typeof PoolTypes
44 * Enumeration of pool events.
46 export const PoolEvents
: Readonly
<{
53 taskError
: 'taskError'
54 backPressure
: 'backPressure'
62 taskError
: 'taskError',
63 backPressure
: 'backPressure'
69 export type PoolEvent
= keyof
typeof PoolEvents
74 export interface PoolInfo
{
75 readonly version
: string
76 readonly type: PoolType
77 readonly worker
: WorkerType
78 readonly started
: boolean
79 readonly ready
: boolean
80 readonly defaultStrategy
: WorkerChoiceStrategy
81 readonly strategyRetries
: number
82 readonly minSize
: number
83 readonly maxSize
: number
84 /** Pool utilization. */
85 readonly utilization
?: number
86 /** Pool total worker nodes. */
87 readonly workerNodes
: number
88 /** Pool stealing worker nodes. */
89 readonly stealingWorkerNodes
?: number
90 /** Pool idle worker nodes. */
91 readonly idleWorkerNodes
: number
92 /** Pool busy worker nodes. */
93 readonly busyWorkerNodes
: number
94 readonly executedTasks
: number
95 readonly executingTasks
: number
96 readonly queuedTasks
?: number
97 readonly maxQueuedTasks
?: number
98 readonly backPressure
?: boolean
99 readonly stolenTasks
?: number
100 readonly failedTasks
: number
102 readonly minimum
: number
103 readonly maximum
: number
104 readonly average
?: number
105 readonly median
?: number
107 readonly waitTime
?: {
108 readonly minimum
: number
109 readonly maximum
: number
110 readonly average
?: number
111 readonly median
?: number
116 * Worker node tasks queue options.
118 export interface TasksQueueOptions
{
120 * Maximum tasks queue size per worker node flagging it as back pressured.
122 * @defaultValue (pool maximum size)^2
124 readonly size
?: number
126 * Maximum number of tasks that can be executed concurrently on a worker node.
130 readonly concurrency
?: number
132 * Whether to enable task stealing on idle.
136 readonly taskStealing
?: boolean
138 * Whether to enable tasks stealing under back pressure.
142 readonly tasksStealingOnBackPressure
?: boolean
144 * Queued tasks finished timeout in milliseconds at worker node termination.
148 readonly tasksFinishedTimeout
?: number
152 * Options for a poolifier pool.
154 * @typeParam Worker - Type of worker.
156 export interface PoolOptions
<Worker
extends IWorker
> {
158 * A function that will listen for online event on each worker.
160 * @defaultValue `() => {}`
162 onlineHandler
?: OnlineHandler
<Worker
>
164 * A function that will listen for message event on each worker.
166 * @defaultValue `() => {}`
168 messageHandler
?: MessageHandler
<Worker
>
170 * A function that will listen for error event on each worker.
172 * @defaultValue `() => {}`
174 errorHandler
?: ErrorHandler
<Worker
>
176 * A function that will listen for exit event on each worker.
178 * @defaultValue `() => {}`
180 exitHandler
?: ExitHandler
<Worker
>
182 * Whether to start the minimum number of workers at pool initialization.
186 startWorkers
?: boolean
188 * The default worker choice strategy to use in this pool.
190 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
192 workerChoiceStrategy
?: WorkerChoiceStrategy
194 * The worker choice strategy options.
196 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
198 * Restart worker on error.
200 restartWorkerOnError
?: boolean
202 * Pool events integrated with async resource emission.
206 enableEvents
?: boolean
208 * Pool worker node tasks queue.
210 * @defaultValue false
212 enableTasksQueue
?: boolean
214 * Pool worker node tasks queue options.
216 tasksQueueOptions
?: TasksQueueOptions
220 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
222 workerOptions
?: WorkerOptions
224 * Key/value pairs to add to worker process environment.
226 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
228 env
?: Record
<string, unknown
>
232 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
234 settings
?: ClusterSettings
238 * Contract definition for a poolifier pool.
240 * @typeParam Worker - Type of worker which manages this pool.
241 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
242 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
244 export interface IPool
<
245 Worker
extends IWorker
,
252 readonly info
: PoolInfo
258 readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>>
260 * Pool event emitter integrated with async resource.
261 * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
263 * Events that can currently be listened to:
265 * - `'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.
266 * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
267 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
268 * - `'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.
269 * - `'destroy'`: Emitted when the pool is destroyed.
270 * - `'error'`: Emitted when an uncaught error occurs.
271 * - `'taskError'`: Emitted when an error occurs while executing a task.
272 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= maximum queue size).
274 readonly emitter
?: EventEmitterAsyncResource
276 * Executes the specified function in the worker constructor with the task data input parameter.
278 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
279 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
280 * @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.
281 * @returns Promise that will be fulfilled when the task is completed.
286 transferList
?: readonly TransferListItem
[]
287 ) => Promise
<Response
>
289 * Starts the minimum number of workers in this pool.
291 readonly start
: () => void
293 * Terminates all workers in this pool.
295 readonly destroy
: () => Promise
<void>
297 * Whether the specified task function exists in this pool.
299 * @param name - The name of the task function.
300 * @returns `true` if the task function exists, `false` otherwise.
302 readonly hasTaskFunction
: (name
: string) => boolean
304 * Adds a task function to this pool.
305 * If a task function with the same name already exists, it will be overwritten.
307 * @param name - The name of the task function.
308 * @param fn - The task function.
309 * @returns `true` if the task function was added, `false` otherwise.
310 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
311 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
313 readonly addTaskFunction
: (
315 fn
: TaskFunction
<Data
, Response
>
316 ) => Promise
<boolean>
318 * Removes a task function from this pool.
320 * @param name - The name of the task function.
321 * @returns `true` if the task function was removed, `false` otherwise.
323 readonly removeTaskFunction
: (name
: string) => Promise
<boolean>
325 * Lists the properties of task functions available in this pool.
327 * @returns The properties of task functions available in this pool.
329 readonly listTaskFunctionsProperties
: () => TaskFunctionProperties
[]
331 * Sets the default task function in this pool.
333 * @param name - The name of the task function.
334 * @returns `true` if the default task function was set, `false` otherwise.
336 readonly setDefaultTaskFunction
: (name
: string) => Promise
<boolean>
338 * Sets the default worker choice strategy in this pool.
340 * @param workerChoiceStrategy - The default worker choice strategy.
341 * @param workerChoiceStrategyOptions - The worker choice strategy options.
343 readonly setWorkerChoiceStrategy
: (
344 workerChoiceStrategy
: WorkerChoiceStrategy
,
345 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
348 * Sets the worker choice strategy options in this pool.
350 * @param workerChoiceStrategyOptions - The worker choice strategy options.
351 * @returns `true` if the worker choice strategy options were set, `false` otherwise.
353 readonly setWorkerChoiceStrategyOptions
: (
354 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
357 * Enables/disables the worker node tasks queue in this pool.
359 * @param enable - Whether to enable or disable the worker node tasks queue.
360 * @param tasksQueueOptions - The worker node tasks queue options.
362 readonly enableTasksQueue
: (
364 tasksQueueOptions
?: TasksQueueOptions
367 * Sets the worker node tasks queue options in this pool.
369 * @param tasksQueueOptions - The worker node tasks queue options.
371 readonly setTasksQueueOptions
: (tasksQueueOptions
: TasksQueueOptions
) => void