refactor: cleanup median computation code
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
2740a743 2import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
bbeadd16
JB
3import {
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
5 EMPTY_FUNCTION,
0d80593b 6 isPlainObject,
bbeadd16
JB
7 median
8} from '../utils'
34a0cfab 9import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
65d7a1c9 10import { CircularArray } from '../circular-array'
29ee7e9a 11import { Queue } from '../queue'
c4855468 12import {
65d7a1c9 13 type IPool,
7c5a1080 14 PoolEmitter,
c4855468 15 PoolEvents,
c4855468 16 type PoolOptions,
65d7a1c9
JB
17 PoolType,
18 type TasksQueueOptions
c4855468 19} from './pool'
f06e48d8 20import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
a35560ba
S
21import {
22 WorkerChoiceStrategies,
a20f0ba5
JB
23 type WorkerChoiceStrategy,
24 type WorkerChoiceStrategyOptions
bdaf31cd
JB
25} from './selection-strategies/selection-strategies-types'
26import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 27
729c563d 28/**
ea7a90d3 29 * Base class that implements some shared logic for all poolifier pools.
729c563d 30 *
38e795c1
JB
31 * @typeParam Worker - Type of worker which manages this pool.
32 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 33 * @typeParam Response - Type of execution response. This can only be serializable data.
729c563d 34 */
c97c7edb 35export abstract class AbstractPool<
f06e48d8 36 Worker extends IWorker,
d3c8a1a8
S
37 Data = unknown,
38 Response = unknown
c4855468 39> implements IPool<Worker, Data, Response> {
afc003b2 40 /** @inheritDoc */
f06e48d8 41 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
4a6952ff 42
afc003b2 43 /** @inheritDoc */
7c0ba920
JB
44 public readonly emitter?: PoolEmitter
45
be0676b3 46 /**
a3445496 47 * The execution response promise map.
be0676b3 48 *
2740a743 49 * - `key`: The message id of each submitted task.
a3445496 50 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
be0676b3 51 *
a3445496 52 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 53 */
c923ce56
JB
54 protected promiseResponseMap: Map<
55 string,
56 PromiseResponseWrapper<Worker, Response>
57 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
c97c7edb 58
a35560ba 59 /**
51fe3d3c 60 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba 61 *
51fe3d3c 62 * Default to a round robin algorithm.
a35560ba
S
63 */
64 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
65 Worker,
66 Data,
67 Response
a35560ba
S
68 >
69
729c563d
S
70 /**
71 * Constructs a new poolifier pool.
72 *
38e795c1 73 * @param numberOfWorkers - Number of workers that this pool should manage.
029715f0 74 * @param filePath - Path to the worker file.
38e795c1 75 * @param opts - Options for the pool.
729c563d 76 */
c97c7edb 77 public constructor (
5c5a1fb7 78 public readonly numberOfWorkers: number,
c97c7edb 79 public readonly filePath: string,
1927ee67 80 public readonly opts: PoolOptions<Worker>
c97c7edb 81 ) {
78cea37e 82 if (!this.isMain()) {
c97c7edb
S
83 throw new Error('Cannot start a pool from a worker!')
84 }
8d3782fa 85 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 86 this.checkFilePath(this.filePath)
7c0ba920 87 this.checkPoolOptions(this.opts)
1086026a 88
7254e419
JB
89 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
90 this.executeTask = this.executeTask.bind(this)
91 this.enqueueTask = this.enqueueTask.bind(this)
92 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
1086026a 93
c97c7edb
S
94 this.setupHook()
95
5c5a1fb7 96 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 97 this.createAndSetupWorker()
c97c7edb
S
98 }
99
6bd72cd0 100 if (this.opts.enableEvents === true) {
7c0ba920
JB
101 this.emitter = new PoolEmitter()
102 }
d59df138
JB
103 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
104 Worker,
105 Data,
106 Response
da309861
JB
107 >(
108 this,
109 this.opts.workerChoiceStrategy,
110 this.opts.workerChoiceStrategyOptions
111 )
c97c7edb
S
112 }
113
a35560ba 114 private checkFilePath (filePath: string): void {
ffcbbad8
JB
115 if (
116 filePath == null ||
117 (typeof filePath === 'string' && filePath.trim().length === 0)
118 ) {
c510fea7
APA
119 throw new Error('Please specify a file with a worker implementation')
120 }
121 }
122
8d3782fa
JB
123 private checkNumberOfWorkers (numberOfWorkers: number): void {
124 if (numberOfWorkers == null) {
125 throw new Error(
126 'Cannot instantiate a pool without specifying the number of workers'
127 )
78cea37e 128 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 129 throw new TypeError(
0d80593b 130 'Cannot instantiate a pool with a non safe integer number of workers'
8d3782fa
JB
131 )
132 } else if (numberOfWorkers < 0) {
473c717a 133 throw new RangeError(
8d3782fa
JB
134 'Cannot instantiate a pool with a negative number of workers'
135 )
7c0ba920 136 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
137 throw new Error('Cannot instantiate a fixed pool with no worker')
138 }
139 }
140
7c0ba920 141 private checkPoolOptions (opts: PoolOptions<Worker>): void {
0d80593b
JB
142 if (isPlainObject(opts)) {
143 this.opts.workerChoiceStrategy =
144 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
145 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
146 this.opts.workerChoiceStrategyOptions =
147 opts.workerChoiceStrategyOptions ??
148 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
49be33fe
JB
149 this.checkValidWorkerChoiceStrategyOptions(
150 this.opts.workerChoiceStrategyOptions
151 )
0d80593b
JB
152 this.opts.enableEvents = opts.enableEvents ?? true
153 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
154 if (this.opts.enableTasksQueue) {
155 this.checkValidTasksQueueOptions(
156 opts.tasksQueueOptions as TasksQueueOptions
157 )
158 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
159 opts.tasksQueueOptions as TasksQueueOptions
160 )
161 }
162 } else {
163 throw new TypeError('Invalid pool options: must be a plain object')
7171d33f 164 }
aee46736
JB
165 }
166
167 private checkValidWorkerChoiceStrategy (
168 workerChoiceStrategy: WorkerChoiceStrategy
169 ): void {
170 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
b529c323 171 throw new Error(
aee46736 172 `Invalid worker choice strategy '${workerChoiceStrategy}'`
b529c323
JB
173 )
174 }
7c0ba920
JB
175 }
176
0d80593b
JB
177 private checkValidWorkerChoiceStrategyOptions (
178 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
179 ): void {
180 if (!isPlainObject(workerChoiceStrategyOptions)) {
181 throw new TypeError(
182 'Invalid worker choice strategy options: must be a plain object'
183 )
184 }
49be33fe
JB
185 if (
186 workerChoiceStrategyOptions.weights != null &&
187 Object.keys(workerChoiceStrategyOptions.weights).length !== this.size
188 ) {
189 throw new Error(
190 'Invalid worker choice strategy options: must have a weight for each worker node'
191 )
192 }
0d80593b
JB
193 }
194
a20f0ba5
JB
195 private checkValidTasksQueueOptions (
196 tasksQueueOptions: TasksQueueOptions
197 ): void {
0d80593b
JB
198 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
199 throw new TypeError('Invalid tasks queue options: must be a plain object')
200 }
a20f0ba5
JB
201 if ((tasksQueueOptions?.concurrency as number) <= 0) {
202 throw new Error(
203 `Invalid worker tasks concurrency '${
204 tasksQueueOptions.concurrency as number
205 }'`
206 )
207 }
208 }
209
afc003b2 210 /** @inheritDoc */
7c0ba920
JB
211 public abstract get type (): PoolType
212
08f3f44c
JB
213 /** @inheritDoc */
214 public abstract get size (): number
215
c2ade475 216 /**
ff733df7 217 * Number of tasks running in the pool.
c2ade475
JB
218 */
219 private get numberOfRunningTasks (): number {
ff733df7
JB
220 return this.workerNodes.reduce(
221 (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
222 0
223 )
224 }
225
226 /**
227 * Number of tasks queued in the pool.
228 */
229 private get numberOfQueuedTasks (): number {
230 if (this.opts.enableTasksQueue === false) {
231 return 0
232 }
233 return this.workerNodes.reduce(
4d8bf9e4 234 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
ff733df7
JB
235 0
236 )
a35560ba
S
237 }
238
ffcbbad8 239 /**
f06e48d8 240 * Gets the given worker its worker node key.
ffcbbad8
JB
241 *
242 * @param worker - The worker.
f06e48d8 243 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
ffcbbad8 244 */
f06e48d8
JB
245 private getWorkerNodeKey (worker: Worker): number {
246 return this.workerNodes.findIndex(
247 workerNode => workerNode.worker === worker
248 )
bf9549ae
JB
249 }
250
afc003b2 251 /** @inheritDoc */
a35560ba 252 public setWorkerChoiceStrategy (
59219cbb
JB
253 workerChoiceStrategy: WorkerChoiceStrategy,
254 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 255 ): void {
aee46736 256 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
b98ec2e6 257 this.opts.workerChoiceStrategy = workerChoiceStrategy
0ebe2a9f 258 for (const workerNode of this.workerNodes) {
f82cd357
JB
259 this.setWorkerNodeTasksUsage(workerNode, {
260 run: 0,
261 running: 0,
262 runTime: 0,
263 runTimeHistory: new CircularArray(),
264 avgRunTime: 0,
265 medRunTime: 0,
266 error: 0
267 })
ea7a90d3 268 }
a35560ba 269 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
a20f0ba5
JB
270 this.opts.workerChoiceStrategy
271 )
59219cbb
JB
272 if (workerChoiceStrategyOptions != null) {
273 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
274 }
a20f0ba5
JB
275 }
276
277 /** @inheritDoc */
278 public setWorkerChoiceStrategyOptions (
279 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
280 ): void {
0d80593b 281 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
a20f0ba5
JB
282 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
283 this.workerChoiceStrategyContext.setOptions(
284 this.opts.workerChoiceStrategyOptions
a35560ba
S
285 )
286 }
287
a20f0ba5 288 /** @inheritDoc */
8f52842f
JB
289 public enableTasksQueue (
290 enable: boolean,
291 tasksQueueOptions?: TasksQueueOptions
292 ): void {
a20f0ba5 293 if (this.opts.enableTasksQueue === true && !enable) {
ef41a6e6 294 this.flushTasksQueues()
a20f0ba5
JB
295 }
296 this.opts.enableTasksQueue = enable
8f52842f 297 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
a20f0ba5
JB
298 }
299
300 /** @inheritDoc */
8f52842f 301 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
a20f0ba5 302 if (this.opts.enableTasksQueue === true) {
8f52842f
JB
303 this.checkValidTasksQueueOptions(tasksQueueOptions)
304 this.opts.tasksQueueOptions =
305 this.buildTasksQueueOptions(tasksQueueOptions)
a20f0ba5
JB
306 } else {
307 delete this.opts.tasksQueueOptions
308 }
309 }
310
311 private buildTasksQueueOptions (
312 tasksQueueOptions: TasksQueueOptions
313 ): TasksQueueOptions {
314 return {
315 concurrency: tasksQueueOptions?.concurrency ?? 1
316 }
317 }
318
c319c66b
JB
319 /**
320 * Whether the pool is full or not.
321 *
322 * The pool filling boolean status.
323 */
324 protected abstract get full (): boolean
c2ade475 325
c319c66b
JB
326 /**
327 * Whether the pool is busy or not.
328 *
329 * The pool busyness boolean status.
330 */
331 protected abstract get busy (): boolean
7c0ba920 332
c2ade475 333 protected internalBusy (): boolean {
e0ae6100
JB
334 return (
335 this.workerNodes.findIndex(workerNode => {
a4958de2 336 return workerNode.tasksUsage.running === 0
e0ae6100
JB
337 }) === -1
338 )
cb70b19d
JB
339 }
340
afc003b2 341 /** @inheritDoc */
a86b6df1 342 public async execute (data?: Data, name?: string): Promise<Response> {
adc3c320
JB
343 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
344 const submittedTask: Task<Data> = {
a86b6df1 345 name,
e5a5c0fc
JB
346 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
347 data: data ?? ({} as Data),
adc3c320
JB
348 id: crypto.randomUUID()
349 }
2e81254d 350 const res = new Promise<Response>((resolve, reject) => {
02706357 351 this.promiseResponseMap.set(submittedTask.id as string, {
2e81254d
JB
352 resolve,
353 reject,
354 worker: workerNode.worker
355 })
356 })
ff733df7
JB
357 if (
358 this.opts.enableTasksQueue === true &&
7171d33f 359 (this.busy ||
3528c992 360 this.workerNodes[workerNodeKey].tasksUsage.running >=
7171d33f 361 ((this.opts.tasksQueueOptions as TasksQueueOptions)
3528c992 362 .concurrency as number))
ff733df7 363 ) {
26a929d7
JB
364 this.enqueueTask(workerNodeKey, submittedTask)
365 } else {
2e81254d 366 this.executeTask(workerNodeKey, submittedTask)
adc3c320 367 }
b0d6ed8f 368 this.workerChoiceStrategyContext.update(workerNodeKey)
ff733df7 369 this.checkAndEmitEvents()
78cea37e 370 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
371 return res
372 }
c97c7edb 373
afc003b2 374 /** @inheritDoc */
c97c7edb 375 public async destroy (): Promise<void> {
1fbcaa7c 376 await Promise.all(
875a7c37
JB
377 this.workerNodes.map(async (workerNode, workerNodeKey) => {
378 this.flushTasksQueue(workerNodeKey)
f06e48d8 379 await this.destroyWorker(workerNode.worker)
1fbcaa7c
JB
380 })
381 )
c97c7edb
S
382 }
383
4a6952ff 384 /**
f06e48d8 385 * Shutdowns the given worker.
4a6952ff 386 *
f06e48d8 387 * @param worker - A worker within `workerNodes`.
4a6952ff
JB
388 */
389 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 390
729c563d 391 /**
2e81254d 392 * Setup hook to execute code before worker node are created in the abstract constructor.
d99ba5a8 393 * Can be overridden
afc003b2
JB
394 *
395 * @virtual
729c563d 396 */
280c2a77 397 protected setupHook (): void {
d99ba5a8 398 // Intentionally empty
280c2a77 399 }
c97c7edb 400
729c563d 401 /**
280c2a77
S
402 * Should return whether the worker is the main worker or not.
403 */
404 protected abstract isMain (): boolean
405
406 /**
2e81254d 407 * Hook executed before the worker task execution.
bf9549ae 408 * Can be overridden.
729c563d 409 *
f06e48d8 410 * @param workerNodeKey - The worker node key.
729c563d 411 */
2e81254d 412 protected beforeTaskExecutionHook (workerNodeKey: number): void {
f06e48d8 413 ++this.workerNodes[workerNodeKey].tasksUsage.running
c97c7edb
S
414 }
415
c01733f1 416 /**
2e81254d 417 * Hook executed after the worker task execution.
bf9549ae 418 * Can be overridden.
c01733f1 419 *
c923ce56 420 * @param worker - The worker.
38e795c1 421 * @param message - The received message.
c01733f1 422 */
2e81254d 423 protected afterTaskExecutionHook (
c923ce56 424 worker: Worker,
2740a743 425 message: MessageValue<Response>
bf9549ae 426 ): void {
a4958de2
JB
427 const workerNodeKey = this.getWorkerNodeKey(worker)
428 const workerTasksUsage = this.workerNodes[workerNodeKey].tasksUsage
3032893a
JB
429 --workerTasksUsage.running
430 ++workerTasksUsage.run
2740a743
JB
431 if (message.error != null) {
432 ++workerTasksUsage.error
433 }
97a2abc3 434 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
aee46736 435 workerTasksUsage.runTime += message.runTime ?? 0
c6bd2650
JB
436 if (
437 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
438 workerTasksUsage.run !== 0
439 ) {
3032893a
JB
440 workerTasksUsage.avgRunTime =
441 workerTasksUsage.runTime / workerTasksUsage.run
442 }
78099a15
JB
443 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
444 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
445 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
446 }
3032893a 447 }
c01733f1 448 }
449
280c2a77 450 /**
f06e48d8 451 * Chooses a worker node for the next task.
280c2a77 452 *
51fe3d3c 453 * The default uses a round robin algorithm to distribute the load.
280c2a77 454 *
adc3c320 455 * @returns [worker node key, worker node].
280c2a77 456 */
adc3c320 457 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
f06e48d8 458 let workerNodeKey: number
0527b6db 459 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
adc3c320
JB
460 const workerCreated = this.createAndSetupWorker()
461 this.registerWorkerMessageListener(workerCreated, message => {
a4958de2 462 const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated)
17393ac8
JB
463 if (
464 isKillBehavior(KillBehaviors.HARD, message.kill) ||
d2097c13 465 (message.kill != null &&
a4958de2 466 this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0)
17393ac8 467 ) {
ff733df7 468 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
a4958de2 469 this.flushTasksQueue(currentWorkerNodeKey)
7c5a1080 470 void (this.destroyWorker(workerCreated) as Promise<void>)
17393ac8
JB
471 }
472 })
adc3c320 473 workerNodeKey = this.getWorkerNodeKey(workerCreated)
17393ac8 474 } else {
f06e48d8 475 workerNodeKey = this.workerChoiceStrategyContext.execute()
17393ac8 476 }
adc3c320 477 return [workerNodeKey, this.workerNodes[workerNodeKey]]
c97c7edb
S
478 }
479
280c2a77 480 /**
675bb809 481 * Sends a message to the given worker.
280c2a77 482 *
38e795c1
JB
483 * @param worker - The worker which should receive the message.
484 * @param message - The message.
280c2a77
S
485 */
486 protected abstract sendToWorker (
487 worker: Worker,
488 message: MessageValue<Data>
489 ): void
490
4a6952ff 491 /**
f06e48d8 492 * Registers a listener callback on the given worker.
4a6952ff 493 *
38e795c1
JB
494 * @param worker - The worker which should register a listener.
495 * @param listener - The message listener callback.
4a6952ff
JB
496 */
497 protected abstract registerWorkerMessageListener<
4f7fa42a 498 Message extends Data | Response
78cea37e 499 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 500
729c563d
S
501 /**
502 * Returns a newly created worker.
503 */
280c2a77 504 protected abstract createWorker (): Worker
c97c7edb 505
729c563d 506 /**
f06e48d8 507 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
729c563d 508 *
38e795c1 509 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 510 *
38e795c1 511 * @param worker - The newly created worker.
729c563d 512 */
280c2a77 513 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 514
4a6952ff 515 /**
f06e48d8 516 * Creates a new worker and sets it up completely in the pool worker nodes.
4a6952ff
JB
517 *
518 * @returns New, completely set up worker.
519 */
520 protected createAndSetupWorker (): Worker {
bdacc2d2 521 const worker = this.createWorker()
280c2a77 522
35cf1c03 523 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
524 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
525 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
526 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 527 worker.once('exit', () => {
f06e48d8 528 this.removeWorkerNode(worker)
a974afa6 529 })
280c2a77 530
f06e48d8 531 this.pushWorkerNode(worker)
280c2a77
S
532
533 this.afterWorkerSetup(worker)
534
c97c7edb
S
535 return worker
536 }
be0676b3
APA
537
538 /**
ff733df7 539 * This function is the listener registered for each worker message.
be0676b3 540 *
bdacc2d2 541 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
542 */
543 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 544 return message => {
b1989cfd 545 if (message.id != null) {
a3445496 546 // Task execution response received
2740a743 547 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 548 if (promiseResponse != null) {
78cea37e 549 if (message.error != null) {
2740a743 550 promiseResponse.reject(message.error)
a05c10de 551 } else {
2740a743 552 promiseResponse.resolve(message.data as Response)
a05c10de 553 }
2e81254d 554 this.afterTaskExecutionHook(promiseResponse.worker, message)
2740a743 555 this.promiseResponseMap.delete(message.id)
ff733df7
JB
556 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
557 if (
558 this.opts.enableTasksQueue === true &&
416fd65c 559 this.tasksQueueSize(workerNodeKey) > 0
ff733df7 560 ) {
2e81254d
JB
561 this.executeTask(
562 workerNodeKey,
ff733df7
JB
563 this.dequeueTask(workerNodeKey) as Task<Data>
564 )
565 }
be0676b3
APA
566 }
567 }
568 }
be0676b3 569 }
7c0ba920 570
ff733df7
JB
571 private checkAndEmitEvents (): void {
572 if (this.opts.enableEvents === true) {
573 if (this.busy) {
574 this.emitter?.emit(PoolEvents.busy)
575 }
576 if (this.type === PoolType.DYNAMIC && this.full) {
577 this.emitter?.emit(PoolEvents.full)
578 }
164d950a
JB
579 }
580 }
581
0ebe2a9f
JB
582 /**
583 * Sets the given worker node its tasks usage in the pool.
584 *
585 * @param workerNode - The worker node.
586 * @param tasksUsage - The worker node tasks usage.
587 */
588 private setWorkerNodeTasksUsage (
589 workerNode: WorkerNode<Worker, Data>,
590 tasksUsage: TasksUsage
591 ): void {
592 workerNode.tasksUsage = tasksUsage
593 }
594
a05c10de 595 /**
f06e48d8 596 * Pushes the given worker in the pool worker nodes.
ea7a90d3 597 *
38e795c1 598 * @param worker - The worker.
f06e48d8 599 * @returns The worker nodes length.
ea7a90d3 600 */
f06e48d8
JB
601 private pushWorkerNode (worker: Worker): number {
602 return this.workerNodes.push({
ffcbbad8 603 worker,
f82cd357
JB
604 tasksUsage: {
605 run: 0,
606 running: 0,
607 runTime: 0,
608 runTimeHistory: new CircularArray(),
609 avgRunTime: 0,
610 medRunTime: 0,
611 error: 0
612 },
29ee7e9a 613 tasksQueue: new Queue<Task<Data>>()
ea7a90d3
JB
614 })
615 }
c923ce56
JB
616
617 /**
f06e48d8 618 * Sets the given worker in the pool worker nodes.
c923ce56 619 *
f06e48d8 620 * @param workerNodeKey - The worker node key.
c923ce56
JB
621 * @param worker - The worker.
622 * @param tasksUsage - The worker tasks usage.
f06e48d8 623 * @param tasksQueue - The worker task queue.
c923ce56 624 */
f06e48d8
JB
625 private setWorkerNode (
626 workerNodeKey: number,
c923ce56 627 worker: Worker,
f06e48d8 628 tasksUsage: TasksUsage,
29ee7e9a 629 tasksQueue: Queue<Task<Data>>
c923ce56 630 ): void {
f06e48d8 631 this.workerNodes[workerNodeKey] = {
c923ce56 632 worker,
f06e48d8
JB
633 tasksUsage,
634 tasksQueue
c923ce56
JB
635 }
636 }
51fe3d3c
JB
637
638 /**
f06e48d8 639 * Removes the given worker from the pool worker nodes.
51fe3d3c 640 *
f06e48d8 641 * @param worker - The worker.
51fe3d3c 642 */
416fd65c 643 private removeWorkerNode (worker: Worker): void {
f06e48d8
JB
644 const workerNodeKey = this.getWorkerNodeKey(worker)
645 this.workerNodes.splice(workerNodeKey, 1)
646 this.workerChoiceStrategyContext.remove(workerNodeKey)
51fe3d3c 647 }
adc3c320 648
2e81254d
JB
649 private executeTask (workerNodeKey: number, task: Task<Data>): void {
650 this.beforeTaskExecutionHook(workerNodeKey)
651 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
652 }
653
f9f00b5f 654 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
29ee7e9a 655 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
adc3c320
JB
656 }
657
416fd65c 658 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
29ee7e9a 659 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
adc3c320
JB
660 }
661
416fd65c 662 private tasksQueueSize (workerNodeKey: number): number {
4d8bf9e4 663 return this.workerNodes[workerNodeKey].tasksQueue.size
adc3c320 664 }
ff733df7 665
416fd65c
JB
666 private flushTasksQueue (workerNodeKey: number): void {
667 if (this.tasksQueueSize(workerNodeKey) > 0) {
29ee7e9a
JB
668 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
669 this.executeTask(
670 workerNodeKey,
671 this.dequeueTask(workerNodeKey) as Task<Data>
672 )
ff733df7 673 }
ff733df7
JB
674 }
675 }
676
ef41a6e6
JB
677 private flushTasksQueues (): void {
678 for (const [workerNodeKey] of this.workerNodes.entries()) {
679 this.flushTasksQueue(workerNodeKey)
680 }
681 }
c97c7edb 682}