refactor: sensible defaults for worker choice strategy policy
[poolifier.git] / src / pools / pool.ts
CommitLineData
2845f2a5 1import { EventEmitter } from 'node:events'
7d91a8cd 2import { type TransferListItem } from 'node:worker_threads'
bdaf31cd
JB
3import type {
4 ErrorHandler,
5 ExitHandler,
50e66724 6 IWorker,
4b628b48 7 IWorkerNode,
bdaf31cd 8 MessageHandler,
c4855468 9 OnlineHandler,
4b628b48 10 WorkerType
f06e48d8 11} from './worker'
da309861
JB
12import type {
13 WorkerChoiceStrategy,
14 WorkerChoiceStrategyOptions
15} from './selection-strategies/selection-strategies-types'
bdaf31cd 16
c4855468 17/**
6b27d407 18 * Enumeration of pool types.
c4855468 19 */
6b27d407 20export const PoolTypes = Object.freeze({
c4855468
JB
21 /**
22 * Fixed pool type.
23 */
6b27d407 24 fixed: 'fixed',
c4855468
JB
25 /**
26 * Dynamic pool type.
27 */
6b27d407
JB
28 dynamic: 'dynamic'
29} as const)
30
31/**
32 * Pool type.
33 */
34export type PoolType = keyof typeof PoolTypes
c4855468 35
b4904890
JB
36/**
37 * Pool events emitter.
38 */
2845f2a5 39export class PoolEmitter extends EventEmitter {}
b4904890 40
aee46736
JB
41/**
42 * Enumeration of pool events.
43 */
44export const PoolEvents = Object.freeze({
2431bdb4 45 ready: 'ready',
1f68cede 46 busy: 'busy',
ef3891a3
JB
47 full: 'full',
48 destroy: 'destroy',
91ee39ed 49 error: 'error',
671d5154
JB
50 taskError: 'taskError',
51 backPressure: 'backPressure'
aee46736
JB
52} as const)
53
54/**
55 * Pool event.
56 */
57export type PoolEvent = keyof typeof PoolEvents
58
6b27d407
JB
59/**
60 * Pool information.
61 */
62export interface PoolInfo {
4b628b48
JB
63 readonly version: string
64 readonly type: PoolType
65 readonly worker: WorkerType
2431bdb4
JB
66 readonly ready: boolean
67 readonly strategy: WorkerChoiceStrategy
4b628b48
JB
68 readonly minSize: number
69 readonly maxSize: number
aa9eede8 70 /** Pool utilization. */
4b628b48 71 readonly utilization?: number
01a59f3c 72 /** Pool total worker nodes. */
4b628b48 73 readonly workerNodes: number
01a59f3c 74 /** Pool idle worker nodes. */
4b628b48 75 readonly idleWorkerNodes: number
01a59f3c 76 /** Pool busy worker nodes. */
4b628b48
JB
77 readonly busyWorkerNodes: number
78 readonly executedTasks: number
79 readonly executingTasks: number
daf86646
JB
80 readonly queuedTasks?: number
81 readonly maxQueuedTasks?: number
a1763c54 82 readonly backPressure?: boolean
4b628b48
JB
83 readonly failedTasks: number
84 readonly runTime?: {
85 readonly minimum: number
86 readonly maximum: number
87 readonly average: number
88 readonly median?: number
1dcf8b7b 89 }
4b628b48
JB
90 readonly waitTime?: {
91 readonly minimum: number
92 readonly maximum: number
93 readonly average: number
94 readonly median?: number
1dcf8b7b 95 }
6b27d407
JB
96}
97
7171d33f
JB
98/**
99 * Worker tasks queue options.
100 */
101export interface TasksQueueOptions {
102 /**
103 * Maximum number of tasks that can be executed concurrently on a worker.
104 *
105 * @defaultValue 1
106 */
eb7bf744 107 readonly concurrency?: number
7171d33f
JB
108}
109
bdaf31cd
JB
110/**
111 * Options for a poolifier pool.
c319c66b 112 *
d480d708 113 * @typeParam Worker - Type of worker.
bdaf31cd 114 */
50e66724 115export interface PoolOptions<Worker extends IWorker> {
fd04474e
JB
116 /**
117 * A function that will listen for online event on each worker.
118 */
119 onlineHandler?: OnlineHandler<Worker>
bdaf31cd
JB
120 /**
121 * A function that will listen for message event on each worker.
122 */
123 messageHandler?: MessageHandler<Worker>
124 /**
125 * A function that will listen for error event on each worker.
126 */
127 errorHandler?: ErrorHandler<Worker>
bdaf31cd
JB
128 /**
129 * A function that will listen for exit event on each worker.
130 */
131 exitHandler?: ExitHandler<Worker>
132 /**
46e857ca 133 * The worker choice strategy to use in this pool.
d29bce7c 134 *
95ec6006 135 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
bdaf31cd
JB
136 */
137 workerChoiceStrategy?: WorkerChoiceStrategy
da309861
JB
138 /**
139 * The worker choice strategy options.
140 */
141 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
1f68cede
JB
142 /**
143 * Restart worker on error.
144 */
145 restartWorkerOnError?: boolean
bdaf31cd
JB
146 /**
147 * Pool events emission.
148 *
38e795c1 149 * @defaultValue true
bdaf31cd
JB
150 */
151 enableEvents?: boolean
ff733df7
JB
152 /**
153 * Pool worker tasks queue.
154 *
ff733df7
JB
155 * @defaultValue false
156 */
157 enableTasksQueue?: boolean
7171d33f
JB
158 /**
159 * Pool worker tasks queue options.
7171d33f
JB
160 */
161 tasksQueueOptions?: TasksQueueOptions
bdaf31cd 162}
a35560ba 163
729c563d
S
164/**
165 * Contract definition for a poolifier pool.
166 *
c4855468 167 * @typeParam Worker - Type of worker which manages this pool.
e102732c
JB
168 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
169 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
729c563d 170 */
c4855468
JB
171export interface IPool<
172 Worker extends IWorker,
173 Data = unknown,
174 Response = unknown
175> {
08f3f44c 176 /**
6b27d407 177 * Pool information.
08f3f44c 178 */
6b27d407 179 readonly info: PoolInfo
c4855468
JB
180 /**
181 * Pool worker nodes.
9768f49f
JB
182 *
183 * @internal
c4855468 184 */
4b628b48 185 readonly workerNodes: Array<IWorkerNode<Worker, Data>>
e2b31e32
JB
186 /**
187 * Whether the worker node has back pressure (i.e. its tasks queue is full).
188 *
189 * @param workerNodeKey - The worker node key.
190 * @returns `true` if the worker node has back pressure, `false` otherwise.
9768f49f 191 * @internal
e2b31e32
JB
192 */
193 readonly hasWorkerNodeBackPressure: (workerNodeKey: number) => boolean
b4904890
JB
194 /**
195 * Emitter on which events can be listened to.
196 *
197 * Events that can currently be listened to:
198 *
d5024c00 199 * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready.
2431bdb4 200 * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing at least one task.
ef3891a3
JB
201 * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
202 * - '`destroy`': Emitted when the pool is destroyed.
91ee39ed
JB
203 * - `'error'`: Emitted when an uncaught error occurs.
204 * - `'taskError'`: Emitted when an error occurs while executing a task.
445264e8 205 * - `'backPressure'`: Emitted when all worker nodes have back pressure (i.e. their tasks queue is full: queue size \>= pool maximum size^2).
b4904890
JB
206 */
207 readonly emitter?: PoolEmitter
729c563d 208 /**
61aa11a6 209 * Executes the specified function in the worker constructor with the task data input parameter.
729c563d 210 *
7d91a8cd
JB
211 * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
212 * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
213 * @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 214 * @returns Promise that will be fulfilled when the task is completed.
729c563d 215 */
7d91a8cd
JB
216 readonly execute: (
217 data?: Data,
218 name?: string,
219 transferList?: TransferListItem[]
220 ) => Promise<Response>
280c2a77 221 /**
aa9eede8 222 * Terminates all workers in this pool.
280c2a77 223 */
4b628b48 224 readonly destroy: () => Promise<void>
90d7d101
JB
225 /**
226 * Lists the names of task function available in this pool.
227 *
228 * @returns The names of task function available in this pool.
229 */
230 readonly listTaskFunctions: () => string[]
a35560ba 231 /**
bdede008 232 * Sets the worker choice strategy in this pool.
a35560ba 233 *
38e795c1 234 * @param workerChoiceStrategy - The worker choice strategy.
59219cbb 235 * @param workerChoiceStrategyOptions - The worker choice strategy options.
a35560ba 236 */
4b628b48 237 readonly setWorkerChoiceStrategy: (
59219cbb
JB
238 workerChoiceStrategy: WorkerChoiceStrategy,
239 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
240 ) => void
a20f0ba5
JB
241 /**
242 * Sets the worker choice strategy options in this pool.
243 *
244 * @param workerChoiceStrategyOptions - The worker choice strategy options.
245 */
4b628b48 246 readonly setWorkerChoiceStrategyOptions: (
a20f0ba5
JB
247 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
248 ) => void
249 /**
250 * Enables/disables the worker tasks queue in this pool.
251 *
252 * @param enable - Whether to enable or disable the worker tasks queue.
253 * @param tasksQueueOptions - The worker tasks queue options.
254 */
4b628b48 255 readonly enableTasksQueue: (
8f52842f
JB
256 enable: boolean,
257 tasksQueueOptions?: TasksQueueOptions
258 ) => void
a20f0ba5
JB
259 /**
260 * Sets the worker tasks queue options in this pool.
261 *
262 * @param tasksQueueOptions - The worker tasks queue options.
263 */
4b628b48 264 readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void
c97c7edb 265}