Merge pull request #1782 from jerome-benoit/fix-worker-readiness
[poolifier.git] / src / pools / pool.ts
CommitLineData
51280f9b 1import type { TransferListItem, WorkerOptions } from 'node:worker_threads'
f80125ca 2import type { EventEmitterAsyncResource } from 'node:events'
c3719753 3import type { ClusterSettings } from 'node:cluster'
6703b9f4 4import type { TaskFunction } from '../worker/task-functions'
bdaf31cd
JB
5import type {
6 ErrorHandler,
7 ExitHandler,
50e66724 8 IWorker,
4b628b48 9 IWorkerNode,
bdaf31cd 10 MessageHandler,
c4855468 11 OnlineHandler,
4b628b48 12 WorkerType
f06e48d8 13} from './worker'
da309861
JB
14import type {
15 WorkerChoiceStrategy,
16 WorkerChoiceStrategyOptions
17} from './selection-strategies/selection-strategies-types'
bdaf31cd 18
c4855468 19/**
6b27d407 20 * Enumeration of pool types.
c4855468 21 */
6b27d407 22export const PoolTypes = Object.freeze({
c4855468
JB
23 /**
24 * Fixed pool type.
25 */
6b27d407 26 fixed: 'fixed',
c4855468
JB
27 /**
28 * Dynamic pool type.
29 */
6b27d407
JB
30 dynamic: 'dynamic'
31} as const)
32
33/**
34 * Pool type.
35 */
36export type PoolType = keyof typeof PoolTypes
c4855468 37
aee46736
JB
38/**
39 * Enumeration of pool events.
40 */
41export const PoolEvents = Object.freeze({
2431bdb4 42 ready: 'ready',
1f68cede 43 busy: 'busy',
ef3891a3
JB
44 full: 'full',
45 destroy: 'destroy',
91ee39ed 46 error: 'error',
671d5154
JB
47 taskError: 'taskError',
48 backPressure: 'backPressure'
aee46736
JB
49} as const)
50
51/**
52 * Pool event.
53 */
54export type PoolEvent = keyof typeof PoolEvents
55
6b27d407
JB
56/**
57 * Pool information.
58 */
59export interface PoolInfo {
4b628b48
JB
60 readonly version: string
61 readonly type: PoolType
62 readonly worker: WorkerType
47352846 63 readonly started: boolean
2431bdb4
JB
64 readonly ready: boolean
65 readonly strategy: WorkerChoiceStrategy
4b628b48
JB
66 readonly minSize: number
67 readonly maxSize: number
aa9eede8 68 /** Pool utilization. */
4b628b48 69 readonly utilization?: number
01a59f3c 70 /** Pool total worker nodes. */
4b628b48 71 readonly workerNodes: number
01a59f3c 72 /** Pool idle worker nodes. */
4b628b48 73 readonly idleWorkerNodes: number
01a59f3c 74 /** Pool busy worker nodes. */
4b628b48
JB
75 readonly busyWorkerNodes: number
76 readonly executedTasks: number
77 readonly executingTasks: number
daf86646
JB
78 readonly queuedTasks?: number
79 readonly maxQueuedTasks?: number
a1763c54 80 readonly backPressure?: boolean
68cbdc84 81 readonly stolenTasks?: number
4b628b48
JB
82 readonly failedTasks: number
83 readonly runTime?: {
84 readonly minimum: number
85 readonly maximum: number
3baa0837 86 readonly average?: number
4b628b48 87 readonly median?: number
1dcf8b7b 88 }
4b628b48
JB
89 readonly waitTime?: {
90 readonly minimum: number
91 readonly maximum: number
3baa0837 92 readonly average?: number
4b628b48 93 readonly median?: number
1dcf8b7b 94 }
6b27d407
JB
95}
96
7171d33f 97/**
20c6f652 98 * Worker node tasks queue options.
7171d33f
JB
99 */
100export interface TasksQueueOptions {
101 /**
20c6f652
JB
102 * Maximum tasks queue size per worker node flagging it as back pressured.
103 *
104 * @defaultValue (pool maximum size)^2
105 */
ff3f866a 106 readonly size?: number
20c6f652
JB
107 /**
108 * Maximum number of tasks that can be executed concurrently on a worker node.
7171d33f
JB
109 *
110 * @defaultValue 1
111 */
eb7bf744 112 readonly concurrency?: number
47352846 113 /**
65542a35 114 * Whether to enable task stealing on idle.
47352846
JB
115 *
116 * @defaultValue true
117 */
dbd73092 118 readonly taskStealing?: boolean
47352846 119 /**
af98b972 120 * Whether to enable tasks stealing under back pressure.
47352846
JB
121 *
122 * @defaultValue true
123 */
124 readonly tasksStealingOnBackPressure?: boolean
32b141fd
JB
125 /**
126 * Queued tasks finished timeout in milliseconds at worker node termination.
127 *
653eba19 128 * @defaultValue 2000
32b141fd
JB
129 */
130 readonly tasksFinishedTimeout?: number
7171d33f
JB
131}
132
bdaf31cd
JB
133/**
134 * Options for a poolifier pool.
c319c66b 135 *
d480d708 136 * @typeParam Worker - Type of worker.
bdaf31cd 137 */
50e66724 138export interface PoolOptions<Worker extends IWorker> {
fd04474e
JB
139 /**
140 * A function that will listen for online event on each worker.
68f1f531
JB
141 *
142 * @defaultValue `() => {}`
fd04474e
JB
143 */
144 onlineHandler?: OnlineHandler<Worker>
bdaf31cd
JB
145 /**
146 * A function that will listen for message event on each worker.
68f1f531
JB
147 *
148 * @defaultValue `() => {}`
bdaf31cd
JB
149 */
150 messageHandler?: MessageHandler<Worker>
151 /**
152 * A function that will listen for error event on each worker.
68f1f531
JB
153 *
154 * @defaultValue `() => {}`
bdaf31cd
JB
155 */
156 errorHandler?: ErrorHandler<Worker>
bdaf31cd
JB
157 /**
158 * A function that will listen for exit event on each worker.
68f1f531
JB
159 *
160 * @defaultValue `() => {}`
bdaf31cd
JB
161 */
162 exitHandler?: ExitHandler<Worker>
47352846
JB
163 /**
164 * Whether to start the minimum number of workers at pool initialization.
165 *
8ff61e33 166 * @defaultValue true
47352846
JB
167 */
168 startWorkers?: boolean
bdaf31cd 169 /**
46e857ca 170 * The worker choice strategy to use in this pool.
d29bce7c 171 *
95ec6006 172 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
bdaf31cd
JB
173 */
174 workerChoiceStrategy?: WorkerChoiceStrategy
da309861
JB
175 /**
176 * The worker choice strategy options.
177 */
178 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
1f68cede
JB
179 /**
180 * Restart worker on error.
181 */
182 restartWorkerOnError?: boolean
bdaf31cd 183 /**
b5604034 184 * Pool events integrated with async resource emission.
bdaf31cd 185 *
38e795c1 186 * @defaultValue true
bdaf31cd
JB
187 */
188 enableEvents?: boolean
ff733df7 189 /**
20c6f652 190 * Pool worker node tasks queue.
ff733df7 191 *
ff733df7
JB
192 * @defaultValue false
193 */
194 enableTasksQueue?: boolean
7171d33f 195 /**
20c6f652 196 * Pool worker node tasks queue options.
7171d33f
JB
197 */
198 tasksQueueOptions?: TasksQueueOptions
c3719753
JB
199 /**
200 * Worker options.
201 *
202 * @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
203 */
204 workerOptions?: WorkerOptions
205 /**
206 * Key/value pairs to add to worker process environment.
207 *
208 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
209 */
210 env?: Record<string, unknown>
211 /**
212 * Cluster settings.
213 *
214 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
215 */
216 settings?: ClusterSettings
bdaf31cd 217}
a35560ba 218
729c563d
S
219/**
220 * Contract definition for a poolifier pool.
221 *
c4855468 222 * @typeParam Worker - Type of worker which manages this pool.
e102732c
JB
223 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
224 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
729c563d 225 */
c4855468
JB
226export interface IPool<
227 Worker extends IWorker,
228 Data = unknown,
229 Response = unknown
230> {
08f3f44c 231 /**
6b27d407 232 * Pool information.
08f3f44c 233 */
6b27d407 234 readonly info: PoolInfo
c4855468
JB
235 /**
236 * Pool worker nodes.
9768f49f
JB
237 *
238 * @internal
c4855468 239 */
4b628b48 240 readonly workerNodes: Array<IWorkerNode<Worker, Data>>
e2b31e32
JB
241 /**
242 * Whether the worker node has back pressure (i.e. its tasks queue is full).
243 *
244 * @param workerNodeKey - The worker node key.
245 * @returns `true` if the worker node has back pressure, `false` otherwise.
9768f49f 246 * @internal
e2b31e32
JB
247 */
248 readonly hasWorkerNodeBackPressure: (workerNodeKey: number) => boolean
b4904890 249 /**
b5794753 250 * Event emitter integrated with async resource on which events can be listened to.
b5604034 251 * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
b4904890
JB
252 *
253 * Events that can currently be listened to:
254 *
d5024c00 255 * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready.
a9780ad2 256 * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
ef3891a3 257 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
033f1776 258 * - `'destroy'`: Emitted when the pool is destroyed.
91ee39ed
JB
259 * - `'error'`: Emitted when an uncaught error occurs.
260 * - `'taskError'`: Emitted when an error occurs while executing a task.
d92f3ddf 261 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= maximum queue size).
b4904890 262 */
f80125ca 263 readonly emitter?: EventEmitterAsyncResource
729c563d 264 /**
61aa11a6 265 * Executes the specified function in the worker constructor with the task data input parameter.
729c563d 266 *
7d91a8cd
JB
267 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
268 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
7379799c 269 * @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.
ef41a6e6 270 * @returns Promise that will be fulfilled when the task is completed.
729c563d 271 */
7d91a8cd
JB
272 readonly execute: (
273 data?: Data,
274 name?: string,
275 transferList?: TransferListItem[]
276 ) => Promise<Response>
47352846
JB
277 /**
278 * Starts the minimum number of workers in this pool.
279 */
280 readonly start: () => void
280c2a77 281 /**
aa9eede8 282 * Terminates all workers in this pool.
280c2a77 283 */
4b628b48 284 readonly destroy: () => Promise<void>
6703b9f4
JB
285 /**
286 * Whether the specified task function exists in this pool.
287 *
288 * @param name - The name of the task function.
289 * @returns `true` if the task function exists, `false` otherwise.
290 */
291 readonly hasTaskFunction: (name: string) => boolean
292 /**
293 * Adds a task function to this pool.
294 * If a task function with the same name already exists, it will be overwritten.
295 *
296 * @param name - The name of the task function.
3feeab69 297 * @param fn - The task function.
6703b9f4 298 * @returns `true` if the task function was added, `false` otherwise.
cf87987c
JB
299 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
300 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
6703b9f4
JB
301 */
302 readonly addTaskFunction: (
303 name: string,
3feeab69 304 fn: TaskFunction<Data, Response>
e81c38f2 305 ) => Promise<boolean>
6703b9f4
JB
306 /**
307 * Removes a task function from this pool.
308 *
309 * @param name - The name of the task function.
310 * @returns `true` if the task function was removed, `false` otherwise.
311 */
e81c38f2 312 readonly removeTaskFunction: (name: string) => Promise<boolean>
90d7d101
JB
313 /**
314 * Lists the names of task function available in this pool.
315 *
316 * @returns The names of task function available in this pool.
317 */
6703b9f4
JB
318 readonly listTaskFunctionNames: () => string[]
319 /**
320 * Sets the default task function in this pool.
321 *
322 * @param name - The name of the task function.
323 * @returns `true` if the default task function was set, `false` otherwise.
324 */
e81c38f2 325 readonly setDefaultTaskFunction: (name: string) => Promise<boolean>
a35560ba 326 /**
bdede008 327 * Sets the worker choice strategy in this pool.
a35560ba 328 *
38e795c1 329 * @param workerChoiceStrategy - The worker choice strategy.
59219cbb 330 * @param workerChoiceStrategyOptions - The worker choice strategy options.
a35560ba 331 */
4b628b48 332 readonly setWorkerChoiceStrategy: (
59219cbb
JB
333 workerChoiceStrategy: WorkerChoiceStrategy,
334 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
335 ) => void
a20f0ba5
JB
336 /**
337 * Sets the worker choice strategy options in this pool.
338 *
339 * @param workerChoiceStrategyOptions - The worker choice strategy options.
340 */
4b628b48 341 readonly setWorkerChoiceStrategyOptions: (
a20f0ba5
JB
342 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
343 ) => void
344 /**
20c6f652 345 * Enables/disables the worker node tasks queue in this pool.
a20f0ba5 346 *
20c6f652
JB
347 * @param enable - Whether to enable or disable the worker node tasks queue.
348 * @param tasksQueueOptions - The worker node tasks queue options.
a20f0ba5 349 */
4b628b48 350 readonly enableTasksQueue: (
8f52842f
JB
351 enable: boolean,
352 tasksQueueOptions?: TasksQueueOptions
353 ) => void
a20f0ba5 354 /**
20c6f652 355 * Sets the worker node tasks queue options in this pool.
a20f0ba5 356 *
20c6f652 357 * @param tasksQueueOptions - The worker node tasks queue options.
a20f0ba5 358 */
4b628b48 359 readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void
c97c7edb 360}