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