refactor: encapsulate worker node handling logic into its own class
[poolifier.git] / src / pools / pool.ts
1 import { EventEmitter } from 'node:events'
2 import type {
3 ErrorHandler,
4 ExitHandler,
5 IWorker,
6 IWorkerNode,
7 MessageHandler,
8 OnlineHandler,
9 WorkerType
10 } from './worker'
11 import type {
12 WorkerChoiceStrategy,
13 WorkerChoiceStrategyOptions
14 } from './selection-strategies/selection-strategies-types'
15
16 /**
17 * Enumeration of pool types.
18 */
19 export const PoolTypes = Object.freeze({
20 /**
21 * Fixed pool type.
22 */
23 fixed: 'fixed',
24 /**
25 * Dynamic pool type.
26 */
27 dynamic: 'dynamic'
28 } as const)
29
30 /**
31 * Pool type.
32 */
33 export type PoolType = keyof typeof PoolTypes
34
35 /**
36 * Pool events emitter.
37 */
38 export class PoolEmitter extends EventEmitter {}
39
40 /**
41 * Enumeration of pool events.
42 */
43 export const PoolEvents = Object.freeze({
44 full: 'full',
45 busy: 'busy',
46 error: 'error',
47 taskError: 'taskError'
48 } as const)
49
50 /**
51 * Pool event.
52 */
53 export type PoolEvent = keyof typeof PoolEvents
54
55 /**
56 * Pool information.
57 */
58 export interface PoolInfo {
59 readonly version: string
60 readonly type: PoolType
61 readonly worker: WorkerType
62 readonly minSize: number
63 readonly maxSize: number
64 /** Pool utilization ratio. */
65 readonly utilization?: number
66 /** Pool total worker nodes */
67 readonly workerNodes: number
68 /** Pool idle worker nodes */
69 readonly idleWorkerNodes: number
70 /** Pool busy worker nodes */
71 readonly busyWorkerNodes: number
72 readonly executedTasks: number
73 readonly executingTasks: number
74 readonly queuedTasks: number
75 readonly maxQueuedTasks: number
76 readonly failedTasks: number
77 readonly runTime?: {
78 readonly minimum: number
79 readonly maximum: number
80 readonly average: number
81 readonly median?: number
82 }
83 readonly waitTime?: {
84 readonly minimum: number
85 readonly maximum: number
86 readonly average: number
87 readonly median?: number
88 }
89 }
90
91 /**
92 * Worker tasks queue options.
93 */
94 export interface TasksQueueOptions {
95 /**
96 * Maximum number of tasks that can be executed concurrently on a worker.
97 *
98 * @defaultValue 1
99 */
100 readonly concurrency?: number
101 }
102
103 /**
104 * Options for a poolifier pool.
105 *
106 * @typeParam Worker - Type of worker.
107 */
108 export interface PoolOptions<Worker extends IWorker> {
109 /**
110 * A function that will listen for message event on each worker.
111 */
112 messageHandler?: MessageHandler<Worker>
113 /**
114 * A function that will listen for error event on each worker.
115 */
116 errorHandler?: ErrorHandler<Worker>
117 /**
118 * A function that will listen for online event on each worker.
119 */
120 onlineHandler?: OnlineHandler<Worker>
121 /**
122 * A function that will listen for exit event on each worker.
123 */
124 exitHandler?: ExitHandler<Worker>
125 /**
126 * The worker choice strategy to use in this pool.
127 *
128 * @defaultValue WorkerChoiceStrategies.ROUND_ROBIN
129 */
130 workerChoiceStrategy?: WorkerChoiceStrategy
131 /**
132 * The worker choice strategy options.
133 */
134 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
135 /**
136 * Restart worker on error.
137 */
138 restartWorkerOnError?: boolean
139 /**
140 * Pool events emission.
141 *
142 * @defaultValue true
143 */
144 enableEvents?: boolean
145 /**
146 * Pool worker tasks queue.
147 *
148 * @defaultValue false
149 */
150 enableTasksQueue?: boolean
151 /**
152 * Pool worker tasks queue options.
153 */
154 tasksQueueOptions?: TasksQueueOptions
155 }
156
157 /**
158 * Contract definition for a poolifier pool.
159 *
160 * @typeParam Worker - Type of worker which manages this pool.
161 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
162 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
163 */
164 export interface IPool<
165 Worker extends IWorker,
166 Data = unknown,
167 Response = unknown
168 > {
169 /**
170 * Pool information.
171 */
172 readonly info: PoolInfo
173 /**
174 * Pool worker nodes.
175 */
176 readonly workerNodes: Array<IWorkerNode<Worker, Data>>
177 /**
178 * Emitter on which events can be listened to.
179 *
180 * Events that can currently be listened to:
181 *
182 * - `'full'`: Emitted when the pool is dynamic and full.
183 * - `'busy'`: Emitted when the pool is busy.
184 * - `'error'`: Emitted when an uncaught error occurs.
185 * - `'taskError'`: Emitted when an error occurs while executing a task.
186 */
187 readonly emitter?: PoolEmitter
188 /**
189 * Executes the specified function in the worker constructor with the task data input parameter.
190 *
191 * @param data - The task input data for the specified worker function. This can only be structured-cloneable data.
192 * @param name - The name of the worker function to execute. If not specified, the default worker function will be executed.
193 * @returns Promise that will be fulfilled when the task is completed.
194 */
195 readonly execute: (data?: Data, name?: string) => Promise<Response>
196 /**
197 * Terminates every current worker in this pool.
198 */
199 readonly destroy: () => Promise<void>
200 /**
201 * Sets the worker choice strategy in this pool.
202 *
203 * @param workerChoiceStrategy - The worker choice strategy.
204 * @param workerChoiceStrategyOptions - The worker choice strategy options.
205 */
206 readonly setWorkerChoiceStrategy: (
207 workerChoiceStrategy: WorkerChoiceStrategy,
208 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
209 ) => void
210 /**
211 * Sets the worker choice strategy options in this pool.
212 *
213 * @param workerChoiceStrategyOptions - The worker choice strategy options.
214 */
215 readonly setWorkerChoiceStrategyOptions: (
216 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
217 ) => void
218 /**
219 * Enables/disables the worker tasks queue in this pool.
220 *
221 * @param enable - Whether to enable or disable the worker tasks queue.
222 * @param tasksQueueOptions - The worker tasks queue options.
223 */
224 readonly enableTasksQueue: (
225 enable: boolean,
226 tasksQueueOptions?: TasksQueueOptions
227 ) => void
228 /**
229 * Sets the worker tasks queue options in this pool.
230 *
231 * @param tasksQueueOptions - The worker tasks queue options.
232 */
233 readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void
234 }