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