a840dc740116057f8fa7867f85348a676caf04a4
[poolifier.git] / src / pools / abstract-pool.ts
1 import crypto from 'node:crypto'
2 import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
3 import { EMPTY_FUNCTION, median } from '../utils'
4 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
5 import { PoolEvents, type PoolOptions } from './pool'
6 import { PoolEmitter } from './pool'
7 import type { IPoolInternal } from './pool-internal'
8 import { PoolType } from './pool-internal'
9 import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
10 import {
11 WorkerChoiceStrategies,
12 type WorkerChoiceStrategy
13 } from './selection-strategies/selection-strategies-types'
14 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
15 import { CircularArray } from '../circular-array'
16
17 /**
18 * Base class that implements some shared logic for all poolifier pools.
19 *
20 * @typeParam Worker - Type of worker which manages this pool.
21 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
22 * @typeParam Response - Type of response of execution. This can only be serializable data.
23 */
24 export abstract class AbstractPool<
25 Worker extends IWorker,
26 Data = unknown,
27 Response = unknown
28 > implements IPoolInternal<Worker, Data, Response> {
29 /** @inheritDoc */
30 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
31
32 /** @inheritDoc */
33 public readonly emitter?: PoolEmitter
34
35 /**
36 * The execution response promise map.
37 *
38 * - `key`: The message id of each submitted task.
39 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
40 *
41 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
42 */
43 protected promiseResponseMap: Map<
44 string,
45 PromiseResponseWrapper<Worker, Response>
46 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
47
48 /**
49 * Worker choice strategy context referencing a worker choice algorithm implementation.
50 *
51 * Default to a round robin algorithm.
52 */
53 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
54 Worker,
55 Data,
56 Response
57 >
58
59 /**
60 * Constructs a new poolifier pool.
61 *
62 * @param numberOfWorkers - Number of workers that this pool should manage.
63 * @param filePath - Path to the worker-file.
64 * @param opts - Options for the pool.
65 */
66 public constructor (
67 public readonly numberOfWorkers: number,
68 public readonly filePath: string,
69 public readonly opts: PoolOptions<Worker>
70 ) {
71 if (!this.isMain()) {
72 throw new Error('Cannot start a pool from a worker!')
73 }
74 this.checkNumberOfWorkers(this.numberOfWorkers)
75 this.checkFilePath(this.filePath)
76 this.checkPoolOptions(this.opts)
77
78 this.chooseWorkerNode.bind(this)
79 this.executeTask.bind(this)
80 this.enqueueTask.bind(this)
81 this.checkAndEmitEvents.bind(this)
82
83 this.setupHook()
84
85 for (let i = 1; i <= this.numberOfWorkers; i++) {
86 this.createAndSetupWorker()
87 }
88
89 if (this.opts.enableEvents === true) {
90 this.emitter = new PoolEmitter()
91 }
92 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
93 Worker,
94 Data,
95 Response
96 >(
97 this,
98 this.opts.workerChoiceStrategy,
99 this.opts.workerChoiceStrategyOptions
100 )
101 }
102
103 private checkFilePath (filePath: string): void {
104 if (
105 filePath == null ||
106 (typeof filePath === 'string' && filePath.trim().length === 0)
107 ) {
108 throw new Error('Please specify a file with a worker implementation')
109 }
110 }
111
112 private checkNumberOfWorkers (numberOfWorkers: number): void {
113 if (numberOfWorkers == null) {
114 throw new Error(
115 'Cannot instantiate a pool without specifying the number of workers'
116 )
117 } else if (!Number.isSafeInteger(numberOfWorkers)) {
118 throw new TypeError(
119 'Cannot instantiate a pool with a non integer number of workers'
120 )
121 } else if (numberOfWorkers < 0) {
122 throw new RangeError(
123 'Cannot instantiate a pool with a negative number of workers'
124 )
125 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
126 throw new Error('Cannot instantiate a fixed pool with no worker')
127 }
128 }
129
130 private checkPoolOptions (opts: PoolOptions<Worker>): void {
131 this.opts.workerChoiceStrategy =
132 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
133 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
134 this.opts.workerChoiceStrategyOptions =
135 opts.workerChoiceStrategyOptions ?? { medRunTime: false }
136 this.opts.enableEvents = opts.enableEvents ?? true
137 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
138 }
139
140 private checkValidWorkerChoiceStrategy (
141 workerChoiceStrategy: WorkerChoiceStrategy
142 ): void {
143 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
144 throw new Error(
145 `Invalid worker choice strategy '${workerChoiceStrategy}'`
146 )
147 }
148 }
149
150 /** @inheritDoc */
151 public abstract get type (): PoolType
152
153 /**
154 * Number of tasks running in the pool.
155 */
156 private get numberOfRunningTasks (): number {
157 return this.workerNodes.reduce(
158 (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
159 0
160 )
161 }
162
163 /**
164 * Number of tasks queued in the pool.
165 */
166 private get numberOfQueuedTasks (): number {
167 if (this.opts.enableTasksQueue === false) {
168 return 0
169 }
170 return this.workerNodes.reduce(
171 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.length,
172 0
173 )
174 }
175
176 /**
177 * Gets the given worker its worker node key.
178 *
179 * @param worker - The worker.
180 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
181 */
182 private getWorkerNodeKey (worker: Worker): number {
183 return this.workerNodes.findIndex(
184 workerNode => workerNode.worker === worker
185 )
186 }
187
188 /** @inheritDoc */
189 public setWorkerChoiceStrategy (
190 workerChoiceStrategy: WorkerChoiceStrategy
191 ): void {
192 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
193 this.opts.workerChoiceStrategy = workerChoiceStrategy
194 for (const workerNode of this.workerNodes) {
195 this.setWorkerNodeTasksUsage(workerNode, {
196 run: 0,
197 running: 0,
198 runTime: 0,
199 runTimeHistory: new CircularArray(),
200 avgRunTime: 0,
201 medRunTime: 0,
202 error: 0
203 })
204 }
205 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
206 workerChoiceStrategy
207 )
208 }
209
210 /** @inheritDoc */
211 public abstract get full (): boolean
212
213 /** @inheritDoc */
214 public abstract get busy (): boolean
215
216 protected internalBusy (): boolean {
217 return this.findFreeWorkerNodeKey() === -1
218 }
219
220 /** @inheritDoc */
221 public findFreeWorkerNodeKey (): number {
222 return this.workerNodes.findIndex(workerNode => {
223 return workerNode.tasksUsage?.running === 0
224 })
225 }
226
227 /** @inheritDoc */
228 public async execute (data: Data): Promise<Response> {
229 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
230 const submittedTask: Task<Data> = {
231 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
232 data: data ?? ({} as Data),
233 id: crypto.randomUUID()
234 }
235 const res = new Promise<Response>((resolve, reject) => {
236 this.promiseResponseMap.set(submittedTask.id, {
237 resolve,
238 reject,
239 worker: workerNode.worker
240 })
241 })
242 if (
243 this.opts.enableTasksQueue === true &&
244 (this.busy || this.workerNodes[workerNodeKey].tasksUsage.running > 0)
245 ) {
246 this.enqueueTask(workerNodeKey, submittedTask)
247 } else {
248 this.executeTask(workerNodeKey, submittedTask)
249 }
250 this.checkAndEmitEvents()
251 // eslint-disable-next-line @typescript-eslint/return-await
252 return res
253 }
254
255 /** @inheritDoc */
256 public async destroy (): Promise<void> {
257 await Promise.all(
258 this.workerNodes.map(async (workerNode, workerNodeKey) => {
259 this.flushTasksQueue(workerNodeKey)
260 await this.destroyWorker(workerNode.worker)
261 })
262 )
263 }
264
265 /**
266 * Shutdowns the given worker.
267 *
268 * @param worker - A worker within `workerNodes`.
269 */
270 protected abstract destroyWorker (worker: Worker): void | Promise<void>
271
272 /**
273 * Setup hook to execute code before worker node are created in the abstract constructor.
274 * Can be overridden
275 *
276 * @virtual
277 */
278 protected setupHook (): void {
279 // Intentionally empty
280 }
281
282 /**
283 * Should return whether the worker is the main worker or not.
284 */
285 protected abstract isMain (): boolean
286
287 /**
288 * Hook executed before the worker task execution.
289 * Can be overridden.
290 *
291 * @param workerNodeKey - The worker node key.
292 */
293 protected beforeTaskExecutionHook (workerNodeKey: number): void {
294 ++this.workerNodes[workerNodeKey].tasksUsage.running
295 }
296
297 /**
298 * Hook executed after the worker task execution.
299 * Can be overridden.
300 *
301 * @param worker - The worker.
302 * @param message - The received message.
303 */
304 protected afterTaskExecutionHook (
305 worker: Worker,
306 message: MessageValue<Response>
307 ): void {
308 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
309 --workerTasksUsage.running
310 ++workerTasksUsage.run
311 if (message.error != null) {
312 ++workerTasksUsage.error
313 }
314 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
315 workerTasksUsage.runTime += message.runTime ?? 0
316 if (
317 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
318 workerTasksUsage.run !== 0
319 ) {
320 workerTasksUsage.avgRunTime =
321 workerTasksUsage.runTime / workerTasksUsage.run
322 }
323 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
324 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
325 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
326 }
327 }
328 }
329
330 /**
331 * Chooses a worker node for the next task.
332 *
333 * The default uses a round robin algorithm to distribute the load.
334 *
335 * @returns [worker node key, worker node].
336 */
337 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
338 let workerNodeKey: number
339 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
340 const workerCreated = this.createAndSetupWorker()
341 this.registerWorkerMessageListener(workerCreated, message => {
342 if (
343 isKillBehavior(KillBehaviors.HARD, message.kill) ||
344 (message.kill != null &&
345 this.getWorkerTasksUsage(workerCreated)?.running === 0)
346 ) {
347 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
348 this.flushTasksQueueByWorker(workerCreated)
349 void this.destroyWorker(workerCreated)
350 }
351 })
352 workerNodeKey = this.getWorkerNodeKey(workerCreated)
353 } else {
354 workerNodeKey = this.workerChoiceStrategyContext.execute()
355 }
356 return [workerNodeKey, this.workerNodes[workerNodeKey]]
357 }
358
359 /**
360 * Sends a message to the given worker.
361 *
362 * @param worker - The worker which should receive the message.
363 * @param message - The message.
364 */
365 protected abstract sendToWorker (
366 worker: Worker,
367 message: MessageValue<Data>
368 ): void
369
370 /**
371 * Registers a listener callback on the given worker.
372 *
373 * @param worker - The worker which should register a listener.
374 * @param listener - The message listener callback.
375 */
376 protected abstract registerWorkerMessageListener<
377 Message extends Data | Response
378 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
379
380 /**
381 * Returns a newly created worker.
382 */
383 protected abstract createWorker (): Worker
384
385 /**
386 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
387 *
388 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
389 *
390 * @param worker - The newly created worker.
391 */
392 protected abstract afterWorkerSetup (worker: Worker): void
393
394 /**
395 * Creates a new worker and sets it up completely in the pool worker nodes.
396 *
397 * @returns New, completely set up worker.
398 */
399 protected createAndSetupWorker (): Worker {
400 const worker = this.createWorker()
401
402 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
403 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
404 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
405 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
406 worker.once('exit', () => {
407 this.removeWorkerNode(worker)
408 })
409
410 this.pushWorkerNode(worker)
411
412 this.afterWorkerSetup(worker)
413
414 return worker
415 }
416
417 /**
418 * This function is the listener registered for each worker message.
419 *
420 * @returns The listener function to execute when a message is received from a worker.
421 */
422 protected workerListener (): (message: MessageValue<Response>) => void {
423 return message => {
424 if (message.id != null) {
425 // Task execution response received
426 const promiseResponse = this.promiseResponseMap.get(message.id)
427 if (promiseResponse != null) {
428 if (message.error != null) {
429 promiseResponse.reject(message.error)
430 } else {
431 promiseResponse.resolve(message.data as Response)
432 }
433 this.afterTaskExecutionHook(promiseResponse.worker, message)
434 this.promiseResponseMap.delete(message.id)
435 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
436 if (
437 this.opts.enableTasksQueue === true &&
438 this.tasksQueueSize(workerNodeKey) > 0
439 ) {
440 this.executeTask(
441 workerNodeKey,
442 this.dequeueTask(workerNodeKey) as Task<Data>
443 )
444 }
445 }
446 }
447 }
448 }
449
450 private checkAndEmitEvents (): void {
451 if (this.opts.enableEvents === true) {
452 if (this.busy) {
453 this.emitter?.emit(PoolEvents.busy)
454 }
455 if (this.type === PoolType.DYNAMIC && this.full) {
456 this.emitter?.emit(PoolEvents.full)
457 }
458 }
459 }
460
461 /**
462 * Sets the given worker node its tasks usage in the pool.
463 *
464 * @param workerNode - The worker node.
465 * @param tasksUsage - The worker node tasks usage.
466 */
467 private setWorkerNodeTasksUsage (
468 workerNode: WorkerNode<Worker, Data>,
469 tasksUsage: TasksUsage
470 ): void {
471 workerNode.tasksUsage = tasksUsage
472 }
473
474 /**
475 * Gets the given worker its tasks usage in the pool.
476 *
477 * @param worker - The worker.
478 * @returns The worker tasks usage.
479 */
480 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
481 const workerNodeKey = this.getWorkerNodeKey(worker)
482 if (workerNodeKey !== -1) {
483 return this.workerNodes[workerNodeKey].tasksUsage
484 }
485 throw new Error('Worker could not be found in the pool worker nodes')
486 }
487
488 /**
489 * Pushes the given worker in the pool worker nodes.
490 *
491 * @param worker - The worker.
492 * @returns The worker nodes length.
493 */
494 private pushWorkerNode (worker: Worker): number {
495 return this.workerNodes.push({
496 worker,
497 tasksUsage: {
498 run: 0,
499 running: 0,
500 runTime: 0,
501 runTimeHistory: new CircularArray(),
502 avgRunTime: 0,
503 medRunTime: 0,
504 error: 0
505 },
506 tasksQueue: []
507 })
508 }
509
510 /**
511 * Sets the given worker in the pool worker nodes.
512 *
513 * @param workerNodeKey - The worker node key.
514 * @param worker - The worker.
515 * @param tasksUsage - The worker tasks usage.
516 * @param tasksQueue - The worker task queue.
517 */
518 private setWorkerNode (
519 workerNodeKey: number,
520 worker: Worker,
521 tasksUsage: TasksUsage,
522 tasksQueue: Array<Task<Data>>
523 ): void {
524 this.workerNodes[workerNodeKey] = {
525 worker,
526 tasksUsage,
527 tasksQueue
528 }
529 }
530
531 /**
532 * Removes the given worker from the pool worker nodes.
533 *
534 * @param worker - The worker.
535 */
536 private removeWorkerNode (worker: Worker): void {
537 const workerNodeKey = this.getWorkerNodeKey(worker)
538 this.workerNodes.splice(workerNodeKey, 1)
539 this.workerChoiceStrategyContext.remove(workerNodeKey)
540 }
541
542 private executeTask (workerNodeKey: number, task: Task<Data>): void {
543 this.beforeTaskExecutionHook(workerNodeKey)
544 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
545 }
546
547 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
548 return this.workerNodes[workerNodeKey].tasksQueue.push(task)
549 }
550
551 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
552 return this.workerNodes[workerNodeKey].tasksQueue.shift()
553 }
554
555 private tasksQueueSize (workerNodeKey: number): number {
556 return this.workerNodes[workerNodeKey].tasksQueue.length
557 }
558
559 private flushTasksQueue (workerNodeKey: number): void {
560 if (this.tasksQueueSize(workerNodeKey) > 0) {
561 for (const task of this.workerNodes[workerNodeKey].tasksQueue) {
562 this.executeTask(workerNodeKey, task)
563 }
564 }
565 }
566
567 private flushTasksQueueByWorker (worker: Worker): void {
568 const workerNodeKey = this.getWorkerNodeKey(worker)
569 this.flushTasksQueue(workerNodeKey)
570 }
571 }