fix: ensure not more than one task is executed on a worker with tasks
[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.internalExecute.bind(this)
80 this.checkAndEmitEvents.bind(this)
81 this.sendToWorker.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 (
218 this.numberOfRunningTasks >= this.numberOfWorkers &&
219 this.findFreeWorkerNodeKey() === -1
220 )
221 }
222
223 /** @inheritDoc */
224 public findFreeWorkerNodeKey (): number {
225 return this.workerNodes.findIndex(workerNode => {
226 return workerNode.tasksUsage?.running === 0
227 })
228 }
229
230 /** @inheritDoc */
231 public async execute (data: Data): Promise<Response> {
232 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
233 const submittedTask: Task<Data> = {
234 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
235 data: data ?? ({} as Data),
236 id: crypto.randomUUID()
237 }
238 const res = this.internalExecute(workerNodeKey, workerNode, submittedTask)
239 if (
240 this.opts.enableTasksQueue === true &&
241 (this.busy || this.workerNodes[workerNodeKey].tasksUsage.running > 0)
242 ) {
243 this.enqueueTask(workerNodeKey, submittedTask)
244 } else {
245 this.sendToWorker(workerNode.worker, submittedTask)
246 }
247 this.checkAndEmitEvents()
248 // eslint-disable-next-line @typescript-eslint/return-await
249 return res
250 }
251
252 /** @inheritDoc */
253 public async destroy (): Promise<void> {
254 await Promise.all(
255 this.workerNodes.map(async workerNode => {
256 this.flushTasksQueueByWorker(workerNode.worker)
257 await this.destroyWorker(workerNode.worker)
258 })
259 )
260 }
261
262 /**
263 * Shutdowns the given worker.
264 *
265 * @param worker - A worker within `workerNodes`.
266 */
267 protected abstract destroyWorker (worker: Worker): void | Promise<void>
268
269 /**
270 * Setup hook to run code before worker node are created in the abstract constructor.
271 * Can be overridden
272 *
273 * @virtual
274 */
275 protected setupHook (): void {
276 // Intentionally empty
277 }
278
279 /**
280 * Should return whether the worker is the main worker or not.
281 */
282 protected abstract isMain (): boolean
283
284 /**
285 * Hook executed before the worker task promise resolution.
286 * Can be overridden.
287 *
288 * @param workerNodeKey - The worker node key.
289 */
290 protected beforePromiseResponseHook (workerNodeKey: number): void {
291 ++this.workerNodes[workerNodeKey].tasksUsage.running
292 }
293
294 /**
295 * Hook executed after the worker task promise resolution.
296 * Can be overridden.
297 *
298 * @param worker - The worker.
299 * @param message - The received message.
300 */
301 protected afterPromiseResponseHook (
302 worker: Worker,
303 message: MessageValue<Response>
304 ): void {
305 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
306 --workerTasksUsage.running
307 ++workerTasksUsage.run
308 if (message.error != null) {
309 ++workerTasksUsage.error
310 }
311 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
312 workerTasksUsage.runTime += message.runTime ?? 0
313 if (
314 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
315 workerTasksUsage.run !== 0
316 ) {
317 workerTasksUsage.avgRunTime =
318 workerTasksUsage.runTime / workerTasksUsage.run
319 }
320 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
321 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
322 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
323 }
324 }
325 }
326
327 /**
328 * Chooses a worker node for the next task.
329 *
330 * The default uses a round robin algorithm to distribute the load.
331 *
332 * @returns [worker node key, worker node].
333 */
334 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
335 let workerNodeKey: number
336 if (
337 this.type === PoolType.DYNAMIC &&
338 !this.full &&
339 this.findFreeWorkerNodeKey() === -1
340 ) {
341 const workerCreated = this.createAndSetupWorker()
342 this.registerWorkerMessageListener(workerCreated, message => {
343 if (
344 isKillBehavior(KillBehaviors.HARD, message.kill) ||
345 (message.kill != null &&
346 this.getWorkerTasksUsage(workerCreated)?.running === 0)
347 ) {
348 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
349 this.flushTasksQueueByWorker(workerCreated)
350 void this.destroyWorker(workerCreated)
351 }
352 })
353 workerNodeKey = this.getWorkerNodeKey(workerCreated)
354 } else {
355 workerNodeKey = this.workerChoiceStrategyContext.execute()
356 }
357 return [workerNodeKey, this.workerNodes[workerNodeKey]]
358 }
359
360 /**
361 * Sends a message to the given worker.
362 *
363 * @param worker - The worker which should receive the message.
364 * @param message - The message.
365 */
366 protected abstract sendToWorker (
367 worker: Worker,
368 message: MessageValue<Data>
369 ): void
370
371 /**
372 * Registers a listener callback on the given worker.
373 *
374 * @param worker - The worker which should register a listener.
375 * @param listener - The message listener callback.
376 */
377 protected abstract registerWorkerMessageListener<
378 Message extends Data | Response
379 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
380
381 /**
382 * Returns a newly created worker.
383 */
384 protected abstract createWorker (): Worker
385
386 /**
387 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
388 *
389 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
390 *
391 * @param worker - The newly created worker.
392 */
393 protected abstract afterWorkerSetup (worker: Worker): void
394
395 /**
396 * Creates a new worker and sets it up completely in the pool worker nodes.
397 *
398 * @returns New, completely set up worker.
399 */
400 protected createAndSetupWorker (): Worker {
401 const worker = this.createWorker()
402
403 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
404 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
405 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
406 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
407 worker.once('exit', () => {
408 this.removeWorkerNode(worker)
409 })
410
411 this.pushWorkerNode(worker)
412
413 this.afterWorkerSetup(worker)
414
415 return worker
416 }
417
418 /**
419 * This function is the listener registered for each worker message.
420 *
421 * @returns The listener function to execute when a message is received from a worker.
422 */
423 protected workerListener (): (message: MessageValue<Response>) => void {
424 return message => {
425 if (message.id != null) {
426 // Task execution response received
427 const promiseResponse = this.promiseResponseMap.get(message.id)
428 if (promiseResponse != null) {
429 if (message.error != null) {
430 promiseResponse.reject(message.error)
431 } else {
432 promiseResponse.resolve(message.data as Response)
433 }
434 this.afterPromiseResponseHook(promiseResponse.worker, message)
435 this.promiseResponseMap.delete(message.id)
436 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
437 if (
438 this.opts.enableTasksQueue === true &&
439 this.tasksQueueSize(workerNodeKey) > 0
440 ) {
441 this.sendToWorker(
442 promiseResponse.worker,
443 this.dequeueTask(workerNodeKey) as Task<Data>
444 )
445 }
446 }
447 }
448 }
449 }
450
451 private async internalExecute (
452 workerNodeKey: number,
453 workerNode: WorkerNode<Worker, Data>,
454 task: Task<Data>
455 ): Promise<Response> {
456 this.beforePromiseResponseHook(workerNodeKey)
457 return await new Promise<Response>((resolve, reject) => {
458 this.promiseResponseMap.set(task.id, {
459 resolve,
460 reject,
461 worker: workerNode.worker
462 })
463 })
464 }
465
466 private checkAndEmitEvents (): void {
467 if (this.opts.enableEvents === true) {
468 if (this.busy) {
469 this.emitter?.emit(PoolEvents.busy)
470 }
471 if (this.type === PoolType.DYNAMIC && this.full) {
472 this.emitter?.emit(PoolEvents.full)
473 }
474 }
475 }
476
477 /**
478 * Sets the given worker node its tasks usage in the pool.
479 *
480 * @param workerNode - The worker node.
481 * @param tasksUsage - The worker node tasks usage.
482 */
483 private setWorkerNodeTasksUsage (
484 workerNode: WorkerNode<Worker, Data>,
485 tasksUsage: TasksUsage
486 ): void {
487 workerNode.tasksUsage = tasksUsage
488 }
489
490 /**
491 * Gets the given worker its tasks usage in the pool.
492 *
493 * @param worker - The worker.
494 * @returns The worker tasks usage.
495 */
496 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
497 const workerNodeKey = this.getWorkerNodeKey(worker)
498 if (workerNodeKey !== -1) {
499 return this.workerNodes[workerNodeKey].tasksUsage
500 }
501 throw new Error('Worker could not be found in the pool worker nodes')
502 }
503
504 /**
505 * Pushes the given worker in the pool worker nodes.
506 *
507 * @param worker - The worker.
508 * @returns The worker nodes length.
509 */
510 private pushWorkerNode (worker: Worker): number {
511 return this.workerNodes.push({
512 worker,
513 tasksUsage: {
514 run: 0,
515 running: 0,
516 runTime: 0,
517 runTimeHistory: new CircularArray(),
518 avgRunTime: 0,
519 medRunTime: 0,
520 error: 0
521 },
522 tasksQueue: []
523 })
524 }
525
526 /**
527 * Sets the given worker in the pool worker nodes.
528 *
529 * @param workerNodeKey - The worker node key.
530 * @param worker - The worker.
531 * @param tasksUsage - The worker tasks usage.
532 * @param tasksQueue - The worker task queue.
533 */
534 private setWorkerNode (
535 workerNodeKey: number,
536 worker: Worker,
537 tasksUsage: TasksUsage,
538 tasksQueue: Array<Task<Data>>
539 ): void {
540 this.workerNodes[workerNodeKey] = {
541 worker,
542 tasksUsage,
543 tasksQueue
544 }
545 }
546
547 /**
548 * Removes the given worker from the pool worker nodes.
549 *
550 * @param worker - The worker.
551 */
552 private removeWorkerNode (worker: Worker): void {
553 const workerNodeKey = this.getWorkerNodeKey(worker)
554 this.workerNodes.splice(workerNodeKey, 1)
555 this.workerChoiceStrategyContext.remove(workerNodeKey)
556 }
557
558 private enqueueTask (workerNodeKey: number, task: Task<Data>): void {
559 this.workerNodes[workerNodeKey].tasksQueue.push(task)
560 }
561
562 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
563 return this.workerNodes[workerNodeKey].tasksQueue.shift()
564 }
565
566 private tasksQueueSize (workerNodeKey: number): number {
567 return this.workerNodes[workerNodeKey].tasksQueue.length
568 }
569
570 private flushTasksQueue (workerNodeKey: number): void {
571 if (this.tasksQueueSize(workerNodeKey) > 0) {
572 for (const task of this.workerNodes[workerNodeKey].tasksQueue) {
573 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
574 }
575 this.workerNodes[workerNodeKey].tasksQueue = []
576 }
577 }
578
579 private flushTasksQueueByWorker (worker: Worker): void {
580 const workerNodeKey = this.getWorkerNodeKey(worker)
581 this.flushTasksQueue(workerNodeKey)
582 }
583 }