1 import type { TransferListItem
} from
'node:worker_threads'
2 import type { EventEmitter
, EventEmitterAsyncResource
} from
'node:events'
3 import type { TaskFunction
} from
'../worker/task-functions'
15 WorkerChoiceStrategyOptions
16 } from
'./selection-strategies/selection-strategies-types'
19 * Enumeration of pool types.
21 export const PoolTypes
= Object.freeze({
35 export type PoolType
= keyof
typeof PoolTypes
38 * Enumeration of pool events.
40 export const PoolEvents
= Object.freeze({
46 taskError
: 'taskError',
47 backPressure
: 'backPressure'
53 export type PoolEvent
= keyof
typeof PoolEvents
58 export interface PoolInfo
{
59 readonly version
: string
60 readonly type: PoolType
61 readonly worker
: WorkerType
62 readonly started
: boolean
63 readonly ready
: boolean
64 readonly strategy
: WorkerChoiceStrategy
65 readonly minSize
: number
66 readonly maxSize
: number
67 /** Pool utilization. */
68 readonly utilization
?: number
69 /** Pool total worker nodes. */
70 readonly workerNodes
: number
71 /** Pool idle worker nodes. */
72 readonly idleWorkerNodes
: number
73 /** Pool busy worker nodes. */
74 readonly busyWorkerNodes
: number
75 readonly executedTasks
: number
76 readonly executingTasks
: number
77 readonly queuedTasks
?: number
78 readonly maxQueuedTasks
?: number
79 readonly backPressure
?: boolean
80 readonly stolenTasks
?: number
81 readonly failedTasks
: number
83 readonly minimum
: number
84 readonly maximum
: number
85 readonly average
?: number
86 readonly median
?: number
89 readonly minimum
: number
90 readonly maximum
: number
91 readonly average
?: number
92 readonly median
?: number
97 * Worker node tasks queue options.
99 export interface TasksQueueOptions
{
101 * Maximum tasks queue size per worker node flagging it as back pressured.
103 * @defaultValue (pool maximum size)^2
105 readonly size
?: number
107 * Maximum number of tasks that can be executed concurrently on a worker node.
111 readonly concurrency
?: number
113 * Whether to enable task stealing on empty queue.
117 readonly taskStealing
?: boolean
119 * Whether to enable tasks stealing under back pressure.
123 readonly tasksStealingOnBackPressure
?: boolean
127 * Options for a poolifier pool.
129 * @typeParam Worker - Type of worker.
131 export interface PoolOptions
<Worker
extends IWorker
> {
133 * A function that will listen for online event on each worker.
135 * @defaultValue `() => {}`
137 onlineHandler
?: OnlineHandler
<Worker
>
139 * A function that will listen for message event on each worker.
141 * @defaultValue `() => {}`
143 messageHandler
?: MessageHandler
<Worker
>
145 * A function that will listen for error event on each worker.
147 * @defaultValue `() => {}`
149 errorHandler
?: ErrorHandler
<Worker
>
151 * A function that will listen for exit event on each worker.
153 * @defaultValue `() => {}`
155 exitHandler
?: ExitHandler
<Worker
>
157 * Whether to start the minimum number of workers at pool initialization.
161 startWorkers
?: boolean
163 * The worker choice strategy to use in this pool.
165 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
167 workerChoiceStrategy
?: WorkerChoiceStrategy
169 * The worker choice strategy options.
171 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
173 * Restart worker on error.
175 restartWorkerOnError
?: boolean
177 * Pool events integrated with async resource emission.
181 enableEvents
?: boolean
183 * Pool worker node tasks queue.
185 * @defaultValue false
187 enableTasksQueue
?: boolean
189 * Pool worker node tasks queue options.
191 tasksQueueOptions
?: TasksQueueOptions
195 * Contract definition for a poolifier pool.
197 * @typeParam Worker - Type of worker which manages this pool.
198 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
199 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
201 export interface IPool
<
202 Worker
extends IWorker
,
209 readonly info
: PoolInfo
215 readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>>
217 * Whether the worker node has back pressure (i.e. its tasks queue is full).
219 * @param workerNodeKey - The worker node key.
220 * @returns `true` if the worker node has back pressure, `false` otherwise.
223 readonly hasWorkerNodeBackPressure
: (workerNodeKey
: number) => boolean
225 * Event emitter integrated with async resource on which events can be listened to.
226 * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
228 * Events that can currently be listened to:
230 * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready.
231 * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
232 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
233 * - `'destroy'`: Emitted when the pool is destroyed.
234 * - `'error'`: Emitted when an uncaught error occurs.
235 * - `'taskError'`: Emitted when an error occurs while executing a task.
236 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= maximum queue size).
238 readonly emitter
?: EventEmitter
| EventEmitterAsyncResource
240 * Executes the specified function in the worker constructor with the task data input parameter.
242 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
243 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
244 * @param transferList - An optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the pool's worker_threads worker and they should not be used in the main thread afterwards.
245 * @returns Promise that will be fulfilled when the task is completed.
250 transferList
?: TransferListItem
[]
251 ) => Promise
<Response
>
253 * Starts the minimum number of workers in this pool.
255 readonly start
: () => void
257 * Terminates all workers in this pool.
259 readonly destroy
: () => Promise
<void>
261 * Whether the specified task function exists in this pool.
263 * @param name - The name of the task function.
264 * @returns `true` if the task function exists, `false` otherwise.
266 readonly hasTaskFunction
: (name
: string) => boolean
268 * Adds a task function to this pool.
269 * If a task function with the same name already exists, it will be overwritten.
271 * @param name - The name of the task function.
272 * @param fn - The task function.
273 * @returns `true` if the task function was added, `false` otherwise.
274 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
275 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
277 readonly addTaskFunction
: (
279 fn
: TaskFunction
<Data
, Response
>
280 ) => Promise
<boolean>
282 * Removes a task function from this pool.
284 * @param name - The name of the task function.
285 * @returns `true` if the task function was removed, `false` otherwise.
287 readonly removeTaskFunction
: (name
: string) => Promise
<boolean>
289 * Lists the names of task function available in this pool.
291 * @returns The names of task function available in this pool.
293 readonly listTaskFunctionNames
: () => string[]
295 * Sets the default task function in this pool.
297 * @param name - The name of the task function.
298 * @returns `true` if the default task function was set, `false` otherwise.
300 readonly setDefaultTaskFunction
: (name
: string) => Promise
<boolean>
302 * Sets the worker choice strategy in this pool.
304 * @param workerChoiceStrategy - The worker choice strategy.
305 * @param workerChoiceStrategyOptions - The worker choice strategy options.
307 readonly setWorkerChoiceStrategy
: (
308 workerChoiceStrategy
: WorkerChoiceStrategy
,
309 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
312 * Sets the worker choice strategy options in this pool.
314 * @param workerChoiceStrategyOptions - The worker choice strategy options.
316 readonly setWorkerChoiceStrategyOptions
: (
317 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
320 * Enables/disables the worker node tasks queue in this pool.
322 * @param enable - Whether to enable or disable the worker node tasks queue.
323 * @param tasksQueueOptions - The worker node tasks queue options.
325 readonly enableTasksQueue
: (
327 tasksQueueOptions
?: TasksQueueOptions
330 * Sets the worker node tasks queue options in this pool.
332 * @param tasksQueueOptions - The worker node tasks queue options.
334 readonly setTasksQueueOptions
: (tasksQueueOptions
: TasksQueueOptions
) => void