refactor: use pool side task functions list for hasTaskFunction()
[poolifier.git] / src / pools / pool.ts
CommitLineData
2845f2a5 1import { EventEmitter } from 'node:events'
7d91a8cd 2import { type TransferListItem } from 'node:worker_threads'
6703b9f4 3import type { TaskFunction } from '../worker/task-functions'
bdaf31cd
JB
4import type {
5 ErrorHandler,
6 ExitHandler,
50e66724 7 IWorker,
4b628b48 8 IWorkerNode,
bdaf31cd 9 MessageHandler,
c4855468 10 OnlineHandler,
4b628b48 11 WorkerType
f06e48d8 12} from './worker'
da309861
JB
13import type {
14 WorkerChoiceStrategy,
15 WorkerChoiceStrategyOptions
16} from './selection-strategies/selection-strategies-types'
bdaf31cd 17
c4855468 18/**
6b27d407 19 * Enumeration of pool types.
c4855468 20 */
6b27d407 21export const PoolTypes = Object.freeze({
c4855468
JB
22 /**
23 * Fixed pool type.
24 */
6b27d407 25 fixed: 'fixed',
c4855468
JB
26 /**
27 * Dynamic pool type.
28 */
6b27d407
JB
29 dynamic: 'dynamic'
30} as const)
31
32/**
33 * Pool type.
34 */
35export type PoolType = keyof typeof PoolTypes
c4855468 36
b4904890
JB
37/**
38 * Pool events emitter.
39 */
2845f2a5 40export class PoolEmitter extends EventEmitter {}
b4904890 41
aee46736
JB
42/**
43 * Enumeration of pool events.
44 */
45export const PoolEvents = Object.freeze({
2431bdb4 46 ready: 'ready',
1f68cede 47 busy: 'busy',
ef3891a3
JB
48 full: 'full',
49 destroy: 'destroy',
91ee39ed 50 error: 'error',
671d5154
JB
51 taskError: 'taskError',
52 backPressure: 'backPressure'
aee46736
JB
53} as const)
54
55/**
56 * Pool event.
57 */
58export type PoolEvent = keyof typeof PoolEvents
59
6b27d407
JB
60/**
61 * Pool information.
62 */
63export interface PoolInfo {
4b628b48
JB
64 readonly version: string
65 readonly type: PoolType
66 readonly worker: WorkerType
2431bdb4
JB
67 readonly ready: boolean
68 readonly strategy: WorkerChoiceStrategy
4b628b48
JB
69 readonly minSize: number
70 readonly maxSize: number
aa9eede8 71 /** Pool utilization. */
4b628b48 72 readonly utilization?: number
01a59f3c 73 /** Pool total worker nodes. */
4b628b48 74 readonly workerNodes: 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
JB
109 readonly size?: number
110 /**
111 * @deprecated Use `size` instead.
112 */
20c6f652
JB
113 readonly queueMaxSize?: number
114 /**
115 * Maximum number of tasks that can be executed concurrently on a worker node.
7171d33f
JB
116 *
117 * @defaultValue 1
118 */
eb7bf744 119 readonly concurrency?: number
7171d33f
JB
120}
121
bdaf31cd
JB
122/**
123 * Options for a poolifier pool.
c319c66b 124 *
d480d708 125 * @typeParam Worker - Type of worker.
bdaf31cd 126 */
50e66724 127export interface PoolOptions<Worker extends IWorker> {
fd04474e
JB
128 /**
129 * A function that will listen for online event on each worker.
130 */
131 onlineHandler?: OnlineHandler<Worker>
bdaf31cd
JB
132 /**
133 * A function that will listen for message event on each worker.
134 */
135 messageHandler?: MessageHandler<Worker>
136 /**
137 * A function that will listen for error event on each worker.
138 */
139 errorHandler?: ErrorHandler<Worker>
bdaf31cd
JB
140 /**
141 * A function that will listen for exit event on each worker.
142 */
143 exitHandler?: ExitHandler<Worker>
144 /**
46e857ca 145 * The worker choice strategy to use in this pool.
d29bce7c 146 *
95ec6006 147 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
bdaf31cd
JB
148 */
149 workerChoiceStrategy?: WorkerChoiceStrategy
da309861
JB
150 /**
151 * The worker choice strategy options.
152 */
153 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
1f68cede
JB
154 /**
155 * Restart worker on error.
156 */
157 restartWorkerOnError?: boolean
bdaf31cd
JB
158 /**
159 * Pool events emission.
160 *
38e795c1 161 * @defaultValue true
bdaf31cd
JB
162 */
163 enableEvents?: boolean
ff733df7 164 /**
20c6f652 165 * Pool worker node tasks queue.
ff733df7 166 *
ff733df7
JB
167 * @defaultValue false
168 */
169 enableTasksQueue?: boolean
7171d33f 170 /**
20c6f652 171 * Pool worker node tasks queue options.
7171d33f
JB
172 */
173 tasksQueueOptions?: TasksQueueOptions
bdaf31cd 174}
a35560ba 175
729c563d
S
176/**
177 * Contract definition for a poolifier pool.
178 *
c4855468 179 * @typeParam Worker - Type of worker which manages this pool.
e102732c
JB
180 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
181 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
729c563d 182 */
c4855468
JB
183export interface IPool<
184 Worker extends IWorker,
185 Data = unknown,
186 Response = unknown
187> {
08f3f44c 188 /**
6b27d407 189 * Pool information.
08f3f44c 190 */
6b27d407 191 readonly info: PoolInfo
c4855468
JB
192 /**
193 * Pool worker nodes.
9768f49f
JB
194 *
195 * @internal
c4855468 196 */
4b628b48 197 readonly workerNodes: Array<IWorkerNode<Worker, Data>>
e2b31e32
JB
198 /**
199 * Whether the worker node has back pressure (i.e. its tasks queue is full).
200 *
201 * @param workerNodeKey - The worker node key.
202 * @returns `true` if the worker node has back pressure, `false` otherwise.
9768f49f 203 * @internal
e2b31e32
JB
204 */
205 readonly hasWorkerNodeBackPressure: (workerNodeKey: number) => boolean
b4904890
JB
206 /**
207 * Emitter on which events can be listened to.
208 *
209 * Events that can currently be listened to:
210 *
d5024c00 211 * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready.
a9780ad2 212 * - `'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 213 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
033f1776 214 * - `'destroy'`: Emitted when the pool is destroyed.
91ee39ed
JB
215 * - `'error'`: Emitted when an uncaught error occurs.
216 * - `'taskError'`: Emitted when an error occurs while executing a task.
d92f3ddf 217 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= maximum queue size).
b4904890
JB
218 */
219 readonly emitter?: PoolEmitter
729c563d 220 /**
61aa11a6 221 * Executes the specified function in the worker constructor with the task data input parameter.
729c563d 222 *
7d91a8cd
JB
223 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
224 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
225 * @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.
ef41a6e6 226 * @returns Promise that will be fulfilled when the task is completed.
729c563d 227 */
7d91a8cd
JB
228 readonly execute: (
229 data?: Data,
230 name?: string,
231 transferList?: TransferListItem[]
232 ) => Promise<Response>
280c2a77 233 /**
aa9eede8 234 * Terminates all workers in this pool.
280c2a77 235 */
4b628b48 236 readonly destroy: () => Promise<void>
6703b9f4
JB
237 /**
238 * Whether the specified task function exists in this pool.
239 *
240 * @param name - The name of the task function.
241 * @returns `true` if the task function exists, `false` otherwise.
242 */
243 readonly hasTaskFunction: (name: string) => boolean
244 /**
245 * Adds a task function to this pool.
246 * If a task function with the same name already exists, it will be overwritten.
247 *
248 * @param name - The name of the task function.
249 * @param taskFunction - The task function.
250 * @returns `true` if the task function was added, `false` otherwise.
251 */
252 readonly addTaskFunction: (
253 name: string,
254 taskFunction: TaskFunction
255 ) => boolean
256 /**
257 * Removes a task function from this pool.
258 *
259 * @param name - The name of the task function.
260 * @returns `true` if the task function was removed, `false` otherwise.
261 */
262 readonly removeTaskFunction: (name: string) => boolean
90d7d101
JB
263 /**
264 * Lists the names of task function available in this pool.
265 *
266 * @returns The names of task function available in this pool.
267 */
6703b9f4
JB
268 readonly listTaskFunctionNames: () => string[]
269 /**
270 * Sets the default task function in this pool.
271 *
272 * @param name - The name of the task function.
273 * @returns `true` if the default task function was set, `false` otherwise.
274 */
275 readonly setDefaultTaskFunction: (name: string) => boolean
a35560ba 276 /**
bdede008 277 * Sets the worker choice strategy in this pool.
a35560ba 278 *
38e795c1 279 * @param workerChoiceStrategy - The worker choice strategy.
59219cbb 280 * @param workerChoiceStrategyOptions - The worker choice strategy options.
a35560ba 281 */
4b628b48 282 readonly setWorkerChoiceStrategy: (
59219cbb
JB
283 workerChoiceStrategy: WorkerChoiceStrategy,
284 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
285 ) => void
a20f0ba5
JB
286 /**
287 * Sets the worker choice strategy options in this pool.
288 *
289 * @param workerChoiceStrategyOptions - The worker choice strategy options.
290 */
4b628b48 291 readonly setWorkerChoiceStrategyOptions: (
a20f0ba5
JB
292 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
293 ) => void
294 /**
20c6f652 295 * Enables/disables the worker node tasks queue in this pool.
a20f0ba5 296 *
20c6f652
JB
297 * @param enable - Whether to enable or disable the worker node tasks queue.
298 * @param tasksQueueOptions - The worker node tasks queue options.
a20f0ba5 299 */
4b628b48 300 readonly enableTasksQueue: (
8f52842f
JB
301 enable: boolean,
302 tasksQueueOptions?: TasksQueueOptions
303 ) => void
a20f0ba5 304 /**
20c6f652 305 * Sets the worker node tasks queue options in this pool.
a20f0ba5 306 *
20c6f652 307 * @param tasksQueueOptions - The worker node tasks queue options.
a20f0ba5 308 */
4b628b48 309 readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void
c97c7edb 310}