chore: v4.0.12
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
ded253e2 1import { AsyncResource } from 'node:async_hooks'
2845f2a5 2import { randomUUID } from 'node:crypto'
ded253e2 3import { EventEmitterAsyncResource } from 'node:events'
62c15a68 4import { performance } from 'node:perf_hooks'
ef083f7b 5import type { TransferListItem } from 'node:worker_threads'
ded253e2 6
5c4d16da
JB
7import type {
8 MessageValue,
9 PromiseResponseWrapper,
31847469
JB
10 Task,
11 TaskFunctionProperties
d35e5717 12} from '../utility-types.js'
bbeadd16 13import {
ded253e2 14 average,
31847469 15 buildTaskFunctionProperties,
ff128cc9 16 DEFAULT_TASK_NAME,
bbeadd16 17 EMPTY_FUNCTION,
463226a4 18 exponentialDelay,
59317253 19 isKillBehavior,
0d80593b 20 isPlainObject,
90d6701c 21 max,
afe0d5bf 22 median,
90d6701c 23 min,
463226a4
JB
24 round,
25 sleep
d35e5717 26} from '../utils.js'
31847469
JB
27import type {
28 TaskFunction,
29 TaskFunctionObject
30} from '../worker/task-functions.js'
ded253e2 31import { KillBehaviors } from '../worker/worker-options.js'
c4855468 32import {
65d7a1c9 33 type IPool,
c4855468 34 PoolEvents,
6b27d407 35 type PoolInfo,
c4855468 36 type PoolOptions,
6b27d407
JB
37 type PoolType,
38 PoolTypes,
4b628b48 39 type TasksQueueOptions
d35e5717 40} from './pool.js'
a35560ba 41import {
f0d7f803 42 Measurements,
a35560ba 43 WorkerChoiceStrategies,
a20f0ba5
JB
44 type WorkerChoiceStrategy,
45 type WorkerChoiceStrategyOptions
d35e5717 46} from './selection-strategies/selection-strategies-types.js'
bcfb06ce 47import { WorkerChoiceStrategiesContext } from './selection-strategies/worker-choice-strategies-context.js'
bde6b5d7
JB
48import {
49 checkFilePath,
95d1a734 50 checkValidPriority,
bde6b5d7 51 checkValidTasksQueueOptions,
bfc75cca 52 checkValidWorkerChoiceStrategy,
32b141fd 53 getDefaultTasksQueueOptions,
c329fd41
JB
54 updateEluWorkerUsage,
55 updateRunTimeWorkerUsage,
56 updateTaskStatisticsWorkerUsage,
57 updateWaitTimeWorkerUsage,
87347ea8 58 waitWorkerNodeEvents
d35e5717 59} from './utils.js'
ded253e2
JB
60import { version } from './version.js'
61import type {
62 IWorker,
63 IWorkerNode,
64 WorkerInfo,
65 WorkerNodeEventDetail,
66 WorkerType
67} from './worker.js'
68import { WorkerNode } from './worker-node.js'
23ccf9d7 69
729c563d 70/**
ea7a90d3 71 * Base class that implements some shared logic for all poolifier pools.
729c563d 72 *
38e795c1 73 * @typeParam Worker - Type of worker which manages this pool.
e102732c
JB
74 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
75 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
729c563d 76 */
c97c7edb 77export abstract class AbstractPool<
f06e48d8 78 Worker extends IWorker,
d3c8a1a8
S
79 Data = unknown,
80 Response = unknown
c4855468 81> implements IPool<Worker, Data, Response> {
afc003b2 82 /** @inheritDoc */
4b628b48 83 public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
4a6952ff 84
afc003b2 85 /** @inheritDoc */
f80125ca 86 public emitter?: EventEmitterAsyncResource
7c0ba920 87
be0676b3 88 /**
419e8121 89 * The task execution response promise map:
2740a743 90 * - `key`: The message id of each submitted task.
bcfb06ce 91 * - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks, async resource.
be0676b3 92 *
a3445496 93 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 94 */
84781cd6
JB
95 protected promiseResponseMap: Map<
96 `${string}-${string}-${string}-${string}-${string}`,
97 PromiseResponseWrapper<Response>
98 > = new Map<
99 `${string}-${string}-${string}-${string}-${string}`,
100 PromiseResponseWrapper<Response>
101 >()
c97c7edb 102
a35560ba 103 /**
bcfb06ce 104 * Worker choice strategies context referencing worker choice algorithms implementation.
a35560ba 105 */
bcfb06ce 106 protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext<
78cea37e
JB
107 Worker,
108 Data,
109 Response
a35560ba
S
110 >
111
72ae84a2
JB
112 /**
113 * The task functions added at runtime map:
114 * - `key`: The task function name.
31847469 115 * - `value`: The task function object.
72ae84a2 116 */
31847469
JB
117 private readonly taskFunctions: Map<
118 string,
119 TaskFunctionObject<Data, Response>
120 >
72ae84a2 121
15b176e0
JB
122 /**
123 * Whether the pool is started or not.
124 */
125 private started: boolean
47352846
JB
126 /**
127 * Whether the pool is starting or not.
128 */
129 private starting: boolean
711623b8
JB
130 /**
131 * Whether the pool is destroying or not.
132 */
133 private destroying: boolean
b362a929
JB
134 /**
135 * Whether the minimum number of workers is starting or not.
136 */
137 private startingMinimumNumberOfWorkers: boolean
55082af9
JB
138 /**
139 * Whether the pool ready event has been emitted or not.
140 */
141 private readyEventEmitted: boolean
afe0d5bf
JB
142 /**
143 * The start timestamp of the pool.
144 */
97dc65d9 145 private startTimestamp?: number
afe0d5bf 146
729c563d
S
147 /**
148 * Constructs a new poolifier pool.
149 *
00e1bdeb 150 * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
029715f0 151 * @param filePath - Path to the worker file.
38e795c1 152 * @param opts - Options for the pool.
00e1bdeb 153 * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
729c563d 154 */
c97c7edb 155 public constructor (
26ce26ca 156 protected readonly minimumNumberOfWorkers: number,
b4213b7f 157 protected readonly filePath: string,
26ce26ca
JB
158 protected readonly opts: PoolOptions<Worker>,
159 protected readonly maximumNumberOfWorkers?: number
c97c7edb 160 ) {
78cea37e 161 if (!this.isMain()) {
04f45163 162 throw new Error(
8c6d4acf 163 'Cannot start a pool from a worker with the same type as the pool'
04f45163 164 )
c97c7edb 165 }
26ce26ca 166 this.checkPoolType()
bde6b5d7 167 checkFilePath(this.filePath)
26ce26ca 168 this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers)
7c0ba920 169 this.checkPoolOptions(this.opts)
1086026a 170
7254e419
JB
171 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
172 this.executeTask = this.executeTask.bind(this)
173 this.enqueueTask = this.enqueueTask.bind(this)
1086026a 174
6bd72cd0 175 if (this.opts.enableEvents === true) {
e0843544 176 this.initEventEmitter()
7c0ba920 177 }
bcfb06ce 178 this.workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext<
d59df138
JB
179 Worker,
180 Data,
181 Response
da309861
JB
182 >(
183 this,
bcfb06ce
JB
184 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
185 [this.opts.workerChoiceStrategy!],
da309861
JB
186 this.opts.workerChoiceStrategyOptions
187 )
b6b32453
JB
188
189 this.setupHook()
190
31847469 191 this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>()
72ae84a2 192
47352846 193 this.started = false
075e51d1 194 this.starting = false
711623b8 195 this.destroying = false
55082af9 196 this.readyEventEmitted = false
b362a929 197 this.startingMinimumNumberOfWorkers = false
47352846
JB
198 if (this.opts.startWorkers === true) {
199 this.start()
200 }
c97c7edb
S
201 }
202
26ce26ca
JB
203 private checkPoolType (): void {
204 if (this.type === PoolTypes.fixed && this.maximumNumberOfWorkers != null) {
205 throw new Error(
206 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
207 )
208 }
209 }
210
c63a35a0
JB
211 private checkMinimumNumberOfWorkers (
212 minimumNumberOfWorkers: number | undefined
213 ): void {
af7f2788 214 if (minimumNumberOfWorkers == null) {
8d3782fa
JB
215 throw new Error(
216 'Cannot instantiate a pool without specifying the number of workers'
217 )
af7f2788 218 } else if (!Number.isSafeInteger(minimumNumberOfWorkers)) {
473c717a 219 throw new TypeError(
0d80593b 220 'Cannot instantiate a pool with a non safe integer number of workers'
8d3782fa 221 )
af7f2788 222 } else if (minimumNumberOfWorkers < 0) {
473c717a 223 throw new RangeError(
8d3782fa
JB
224 'Cannot instantiate a pool with a negative number of workers'
225 )
af7f2788 226 } else if (this.type === PoolTypes.fixed && minimumNumberOfWorkers === 0) {
2431bdb4
JB
227 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
228 }
229 }
230
7c0ba920 231 private checkPoolOptions (opts: PoolOptions<Worker>): void {
0d80593b 232 if (isPlainObject(opts)) {
47352846 233 this.opts.startWorkers = opts.startWorkers ?? true
c63a35a0 234 checkValidWorkerChoiceStrategy(opts.workerChoiceStrategy)
0d80593b
JB
235 this.opts.workerChoiceStrategy =
236 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
2324f8c9 237 this.checkValidWorkerChoiceStrategyOptions(
c63a35a0 238 opts.workerChoiceStrategyOptions
2324f8c9 239 )
26ce26ca
JB
240 if (opts.workerChoiceStrategyOptions != null) {
241 this.opts.workerChoiceStrategyOptions = opts.workerChoiceStrategyOptions
8990357d 242 }
1f68cede 243 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
0d80593b
JB
244 this.opts.enableEvents = opts.enableEvents ?? true
245 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
246 if (this.opts.enableTasksQueue) {
c63a35a0 247 checkValidTasksQueueOptions(opts.tasksQueueOptions)
0d80593b 248 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
c63a35a0 249 opts.tasksQueueOptions
0d80593b
JB
250 )
251 }
252 } else {
253 throw new TypeError('Invalid pool options: must be a plain object')
7171d33f 254 }
aee46736
JB
255 }
256
0d80593b 257 private checkValidWorkerChoiceStrategyOptions (
c63a35a0 258 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
0d80593b 259 ): void {
2324f8c9
JB
260 if (
261 workerChoiceStrategyOptions != null &&
262 !isPlainObject(workerChoiceStrategyOptions)
263 ) {
0d80593b
JB
264 throw new TypeError(
265 'Invalid worker choice strategy options: must be a plain object'
266 )
267 }
49be33fe 268 if (
2324f8c9 269 workerChoiceStrategyOptions?.weights != null &&
26ce26ca
JB
270 Object.keys(workerChoiceStrategyOptions.weights).length !==
271 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
49be33fe
JB
272 ) {
273 throw new Error(
274 'Invalid worker choice strategy options: must have a weight for each worker node'
275 )
276 }
f0d7f803 277 if (
2324f8c9 278 workerChoiceStrategyOptions?.measurement != null &&
f0d7f803
JB
279 !Object.values(Measurements).includes(
280 workerChoiceStrategyOptions.measurement
281 )
282 ) {
283 throw new Error(
284 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
285 )
286 }
0d80593b
JB
287 }
288
e0843544 289 private initEventEmitter (): void {
5b7d00b4 290 this.emitter = new EventEmitterAsyncResource({
b5604034
JB
291 name: `poolifier:${this.type}-${this.worker}-pool`
292 })
293 }
294
08f3f44c 295 /** @inheritDoc */
6b27d407
JB
296 public get info (): PoolInfo {
297 return {
23ccf9d7 298 version,
6b27d407 299 type: this.type,
184855e6 300 worker: this.worker,
47352846 301 started: this.started,
2431bdb4 302 ready: this.ready,
67f3f2d6 303 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
bcfb06ce
JB
304 defaultStrategy: this.opts.workerChoiceStrategy!,
305 strategyRetries: this.workerChoiceStrategiesContext?.retriesCount ?? 0,
26ce26ca
JB
306 minSize: this.minimumNumberOfWorkers,
307 maxSize: this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers,
bcfb06ce 308 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
f4d0a470 309 .runTime.aggregate === true &&
bcfb06ce 310 this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
c63a35a0
JB
311 .waitTime.aggregate && {
312 utilization: round(this.utilization)
313 }),
6b27d407
JB
314 workerNodes: this.workerNodes.length,
315 idleWorkerNodes: this.workerNodes.reduce(
316 (accumulator, workerNode) =>
f59e1027 317 workerNode.usage.tasks.executing === 0
a4e07f72
JB
318 ? accumulator + 1
319 : accumulator,
6b27d407
JB
320 0
321 ),
5eb72b9e
JB
322 ...(this.opts.enableTasksQueue === true && {
323 stealingWorkerNodes: this.workerNodes.reduce(
324 (accumulator, workerNode) =>
325 workerNode.info.stealing ? accumulator + 1 : accumulator,
326 0
327 )
328 }),
6b27d407 329 busyWorkerNodes: this.workerNodes.reduce(
533a8e22 330 (accumulator, _, workerNodeKey) =>
42c677c1 331 this.isWorkerNodeBusy(workerNodeKey) ? accumulator + 1 : accumulator,
6b27d407
JB
332 0
333 ),
a4e07f72 334 executedTasks: this.workerNodes.reduce(
6b27d407 335 (accumulator, workerNode) =>
f59e1027 336 accumulator + workerNode.usage.tasks.executed,
a4e07f72
JB
337 0
338 ),
339 executingTasks: this.workerNodes.reduce(
340 (accumulator, workerNode) =>
f59e1027 341 accumulator + workerNode.usage.tasks.executing,
6b27d407
JB
342 0
343 ),
daf86646
JB
344 ...(this.opts.enableTasksQueue === true && {
345 queuedTasks: this.workerNodes.reduce(
346 (accumulator, workerNode) =>
347 accumulator + workerNode.usage.tasks.queued,
348 0
349 )
350 }),
351 ...(this.opts.enableTasksQueue === true && {
352 maxQueuedTasks: this.workerNodes.reduce(
353 (accumulator, workerNode) =>
c63a35a0 354 accumulator + (workerNode.usage.tasks.maxQueued ?? 0),
daf86646
JB
355 0
356 )
357 }),
a1763c54
JB
358 ...(this.opts.enableTasksQueue === true && {
359 backPressure: this.hasBackPressure()
360 }),
68cbdc84
JB
361 ...(this.opts.enableTasksQueue === true && {
362 stolenTasks: this.workerNodes.reduce(
363 (accumulator, workerNode) =>
364 accumulator + workerNode.usage.tasks.stolen,
365 0
366 )
367 }),
a4e07f72
JB
368 failedTasks: this.workerNodes.reduce(
369 (accumulator, workerNode) =>
f59e1027 370 accumulator + workerNode.usage.tasks.failed,
a4e07f72 371 0
1dcf8b7b 372 ),
bcfb06ce 373 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
f4d0a470 374 .runTime.aggregate === true && {
1dcf8b7b 375 runTime: {
98e72cda 376 minimum: round(
90d6701c 377 min(
98e72cda 378 ...this.workerNodes.map(
80115618
JB
379 workerNode =>
380 workerNode.usage.runTime.minimum ?? Number.POSITIVE_INFINITY
98e72cda 381 )
1dcf8b7b
JB
382 )
383 ),
98e72cda 384 maximum: round(
90d6701c 385 max(
98e72cda 386 ...this.workerNodes.map(
80115618
JB
387 workerNode =>
388 workerNode.usage.runTime.maximum ?? Number.NEGATIVE_INFINITY
98e72cda 389 )
1dcf8b7b 390 )
98e72cda 391 ),
bcfb06ce 392 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
3baa0837
JB
393 .runTime.average && {
394 average: round(
395 average(
396 this.workerNodes.reduce<number[]>(
397 (accumulator, workerNode) =>
f12182ad
JB
398 accumulator.concat(
399 workerNode.usage.runTime.history.toArray()
400 ),
3baa0837
JB
401 []
402 )
98e72cda 403 )
dc021bcc 404 )
3baa0837 405 }),
bcfb06ce 406 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
98e72cda
JB
407 .runTime.median && {
408 median: round(
409 median(
3baa0837
JB
410 this.workerNodes.reduce<number[]>(
411 (accumulator, workerNode) =>
f12182ad
JB
412 accumulator.concat(
413 workerNode.usage.runTime.history.toArray()
414 ),
3baa0837 415 []
98e72cda
JB
416 )
417 )
418 )
419 })
1dcf8b7b
JB
420 }
421 }),
bcfb06ce 422 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
f4d0a470 423 .waitTime.aggregate === true && {
1dcf8b7b 424 waitTime: {
98e72cda 425 minimum: round(
90d6701c 426 min(
98e72cda 427 ...this.workerNodes.map(
80115618
JB
428 workerNode =>
429 workerNode.usage.waitTime.minimum ?? Number.POSITIVE_INFINITY
98e72cda 430 )
1dcf8b7b
JB
431 )
432 ),
98e72cda 433 maximum: round(
90d6701c 434 max(
98e72cda 435 ...this.workerNodes.map(
80115618
JB
436 workerNode =>
437 workerNode.usage.waitTime.maximum ?? Number.NEGATIVE_INFINITY
98e72cda 438 )
1dcf8b7b 439 )
98e72cda 440 ),
bcfb06ce 441 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
3baa0837
JB
442 .waitTime.average && {
443 average: round(
444 average(
445 this.workerNodes.reduce<number[]>(
446 (accumulator, workerNode) =>
f12182ad
JB
447 accumulator.concat(
448 workerNode.usage.waitTime.history.toArray()
449 ),
3baa0837
JB
450 []
451 )
98e72cda 452 )
dc021bcc 453 )
3baa0837 454 }),
bcfb06ce 455 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
98e72cda
JB
456 .waitTime.median && {
457 median: round(
458 median(
3baa0837
JB
459 this.workerNodes.reduce<number[]>(
460 (accumulator, workerNode) =>
f12182ad
JB
461 accumulator.concat(
462 workerNode.usage.waitTime.history.toArray()
463 ),
3baa0837 464 []
98e72cda
JB
465 )
466 )
467 )
468 })
1dcf8b7b 469 }
533a8e22
JB
470 }),
471 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
472 .elu.aggregate === true && {
473 elu: {
474 idle: {
475 minimum: round(
476 min(
477 ...this.workerNodes.map(
80115618
JB
478 workerNode =>
479 workerNode.usage.elu.idle.minimum ??
480 Number.POSITIVE_INFINITY
533a8e22
JB
481 )
482 )
483 ),
484 maximum: round(
485 max(
486 ...this.workerNodes.map(
80115618
JB
487 workerNode =>
488 workerNode.usage.elu.idle.maximum ??
489 Number.NEGATIVE_INFINITY
533a8e22
JB
490 )
491 )
492 ),
493 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
494 .elu.average && {
495 average: round(
496 average(
497 this.workerNodes.reduce<number[]>(
498 (accumulator, workerNode) =>
f12182ad
JB
499 accumulator.concat(
500 workerNode.usage.elu.idle.history.toArray()
501 ),
533a8e22
JB
502 []
503 )
504 )
505 )
506 }),
507 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
508 .elu.median && {
509 median: round(
510 median(
511 this.workerNodes.reduce<number[]>(
512 (accumulator, workerNode) =>
f12182ad
JB
513 accumulator.concat(
514 workerNode.usage.elu.idle.history.toArray()
515 ),
533a8e22
JB
516 []
517 )
518 )
519 )
520 })
521 },
522 active: {
523 minimum: round(
524 min(
525 ...this.workerNodes.map(
80115618
JB
526 workerNode =>
527 workerNode.usage.elu.active.minimum ??
528 Number.POSITIVE_INFINITY
533a8e22
JB
529 )
530 )
531 ),
532 maximum: round(
533 max(
534 ...this.workerNodes.map(
80115618
JB
535 workerNode =>
536 workerNode.usage.elu.active.maximum ??
537 Number.NEGATIVE_INFINITY
533a8e22
JB
538 )
539 )
540 ),
541 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
542 .elu.average && {
543 average: round(
544 average(
545 this.workerNodes.reduce<number[]>(
546 (accumulator, workerNode) =>
f12182ad
JB
547 accumulator.concat(
548 workerNode.usage.elu.active.history.toArray()
549 ),
533a8e22
JB
550 []
551 )
552 )
553 )
554 }),
555 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
556 .elu.median && {
557 median: round(
558 median(
559 this.workerNodes.reduce<number[]>(
560 (accumulator, workerNode) =>
f12182ad
JB
561 accumulator.concat(
562 workerNode.usage.elu.active.history.toArray()
563 ),
533a8e22
JB
564 []
565 )
566 )
567 )
568 })
be202c2c
JB
569 },
570 utilization: {
571 average: round(
572 average(
573 this.workerNodes.map(
574 workerNode => workerNode.usage.elu.utilization ?? 0
575 )
576 )
577 ),
578 median: round(
579 median(
580 this.workerNodes.map(
581 workerNode => workerNode.usage.elu.utilization ?? 0
582 )
583 )
584 )
533a8e22
JB
585 }
586 }
1dcf8b7b 587 })
6b27d407
JB
588 }
589 }
08f3f44c 590
aa9eede8
JB
591 /**
592 * The pool readiness boolean status.
593 */
2431bdb4 594 private get ready (): boolean {
8e8d9101
JB
595 if (this.empty) {
596 return false
597 }
2431bdb4 598 return (
b97d82d8
JB
599 this.workerNodes.reduce(
600 (accumulator, workerNode) =>
601 !workerNode.info.dynamic && workerNode.info.ready
602 ? accumulator + 1
603 : accumulator,
604 0
26ce26ca 605 ) >= this.minimumNumberOfWorkers
2431bdb4
JB
606 )
607 }
608
8e8d9101
JB
609 /**
610 * The pool emptiness boolean status.
611 */
612 protected get empty (): boolean {
fb43035c 613 return this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0
8e8d9101
JB
614 }
615
afe0d5bf 616 /**
aa9eede8 617 * The approximate pool utilization.
afe0d5bf
JB
618 *
619 * @returns The pool utilization.
620 */
621 private get utilization (): number {
97dc65d9
JB
622 if (this.startTimestamp == null) {
623 return 0
624 }
8e5ca040 625 const poolTimeCapacity =
26ce26ca
JB
626 (performance.now() - this.startTimestamp) *
627 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
afe0d5bf
JB
628 const totalTasksRunTime = this.workerNodes.reduce(
629 (accumulator, workerNode) =>
c63a35a0 630 accumulator + (workerNode.usage.runTime.aggregate ?? 0),
afe0d5bf
JB
631 0
632 )
633 const totalTasksWaitTime = this.workerNodes.reduce(
634 (accumulator, workerNode) =>
c63a35a0 635 accumulator + (workerNode.usage.waitTime.aggregate ?? 0),
afe0d5bf
JB
636 0
637 )
8e5ca040 638 return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
afe0d5bf
JB
639 }
640
8881ae32 641 /**
aa9eede8 642 * The pool type.
8881ae32
JB
643 *
644 * If it is `'dynamic'`, it provides the `max` property.
645 */
646 protected abstract get type (): PoolType
647
184855e6 648 /**
aa9eede8 649 * The worker type.
184855e6
JB
650 */
651 protected abstract get worker (): WorkerType
652
6b813701
JB
653 /**
654 * Checks if the worker id sent in the received message from a worker is valid.
655 *
656 * @param message - The received message.
657 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
658 */
4d159167 659 private checkMessageWorkerId (message: MessageValue<Data | Response>): void {
310de0aa
JB
660 if (message.workerId == null) {
661 throw new Error('Worker message received without worker id')
8e5a7cf9 662 } else if (this.getWorkerNodeKeyByWorkerId(message.workerId) === -1) {
21f710aa
JB
663 throw new Error(
664 `Worker message received from unknown worker '${message.workerId}'`
665 )
666 }
667 }
668
aa9eede8
JB
669 /**
670 * Gets the worker node key given its worker id.
671 *
672 * @param workerId - The worker id.
aad6fb64 673 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
aa9eede8 674 */
72ae84a2 675 private getWorkerNodeKeyByWorkerId (workerId: number | undefined): number {
aad6fb64 676 return this.workerNodes.findIndex(
041dc05b 677 workerNode => workerNode.info.id === workerId
aad6fb64 678 )
aa9eede8
JB
679 }
680
afc003b2 681 /** @inheritDoc */
a35560ba 682 public setWorkerChoiceStrategy (
59219cbb
JB
683 workerChoiceStrategy: WorkerChoiceStrategy,
684 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 685 ): void {
19b8be8b 686 let requireSync = false
bde6b5d7 687 checkValidWorkerChoiceStrategy(workerChoiceStrategy)
85bbc7ab 688 if (workerChoiceStrategyOptions != null) {
423f3b7a 689 requireSync = !this.setWorkerChoiceStrategyOptions(
19b8be8b
JB
690 workerChoiceStrategyOptions
691 )
85bbc7ab
JB
692 }
693 if (workerChoiceStrategy !== this.opts.workerChoiceStrategy) {
694 this.opts.workerChoiceStrategy = workerChoiceStrategy
695 this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy(
696 this.opts.workerChoiceStrategy,
697 this.opts.workerChoiceStrategyOptions
698 )
19b8be8b
JB
699 requireSync = true
700 }
701 if (requireSync) {
85bbc7ab 702 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
91041638 703 this.getWorkerChoiceStrategies(),
85bbc7ab
JB
704 this.opts.workerChoiceStrategyOptions
705 )
19b8be8b 706 for (const workerNodeKey of this.workerNodes.keys()) {
85bbc7ab
JB
707 this.sendStatisticsMessageToWorker(workerNodeKey)
708 }
59219cbb 709 }
a20f0ba5
JB
710 }
711
712 /** @inheritDoc */
713 public setWorkerChoiceStrategyOptions (
c63a35a0 714 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
19b8be8b 715 ): boolean {
0d80593b 716 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
26ce26ca
JB
717 if (workerChoiceStrategyOptions != null) {
718 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
19b8be8b
JB
719 this.workerChoiceStrategiesContext?.setOptions(
720 this.opts.workerChoiceStrategyOptions
721 )
722 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
91041638 723 this.getWorkerChoiceStrategies(),
19b8be8b
JB
724 this.opts.workerChoiceStrategyOptions
725 )
726 for (const workerNodeKey of this.workerNodes.keys()) {
727 this.sendStatisticsMessageToWorker(workerNodeKey)
728 }
729 return true
8990357d 730 }
19b8be8b 731 return false
a35560ba
S
732 }
733
a20f0ba5 734 /** @inheritDoc */
8f52842f
JB
735 public enableTasksQueue (
736 enable: boolean,
737 tasksQueueOptions?: TasksQueueOptions
738 ): void {
a20f0ba5 739 if (this.opts.enableTasksQueue === true && !enable) {
d6ca1416
JB
740 this.unsetTaskStealing()
741 this.unsetTasksStealingOnBackPressure()
ef41a6e6 742 this.flushTasksQueues()
a20f0ba5
JB
743 }
744 this.opts.enableTasksQueue = enable
c63a35a0 745 this.setTasksQueueOptions(tasksQueueOptions)
a20f0ba5
JB
746 }
747
748 /** @inheritDoc */
c63a35a0
JB
749 public setTasksQueueOptions (
750 tasksQueueOptions: TasksQueueOptions | undefined
751 ): void {
a20f0ba5 752 if (this.opts.enableTasksQueue === true) {
bde6b5d7 753 checkValidTasksQueueOptions(tasksQueueOptions)
8f52842f
JB
754 this.opts.tasksQueueOptions =
755 this.buildTasksQueueOptions(tasksQueueOptions)
67f3f2d6
JB
756 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
757 this.setTasksQueueSize(this.opts.tasksQueueOptions.size!)
d6ca1416 758 if (this.opts.tasksQueueOptions.taskStealing === true) {
9f99eb9b 759 this.unsetTaskStealing()
d6ca1416
JB
760 this.setTaskStealing()
761 } else {
762 this.unsetTaskStealing()
763 }
764 if (this.opts.tasksQueueOptions.tasksStealingOnBackPressure === true) {
9f99eb9b 765 this.unsetTasksStealingOnBackPressure()
d6ca1416
JB
766 this.setTasksStealingOnBackPressure()
767 } else {
768 this.unsetTasksStealingOnBackPressure()
769 }
5baee0d7 770 } else if (this.opts.tasksQueueOptions != null) {
a20f0ba5
JB
771 delete this.opts.tasksQueueOptions
772 }
773 }
774
9b38ab2d 775 private buildTasksQueueOptions (
c63a35a0 776 tasksQueueOptions: TasksQueueOptions | undefined
9b38ab2d
JB
777 ): TasksQueueOptions {
778 return {
26ce26ca
JB
779 ...getDefaultTasksQueueOptions(
780 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
781 ),
9b38ab2d
JB
782 ...tasksQueueOptions
783 }
784 }
785
5b49e864 786 private setTasksQueueSize (size: number): void {
20c6f652 787 for (const workerNode of this.workerNodes) {
ff3f866a 788 workerNode.tasksQueueBackPressureSize = size
20c6f652
JB
789 }
790 }
791
d6ca1416 792 private setTaskStealing (): void {
19b8be8b 793 for (const workerNodeKey of this.workerNodes.keys()) {
e44639e9 794 this.workerNodes[workerNodeKey].on('idle', this.handleWorkerNodeIdleEvent)
d6ca1416
JB
795 }
796 }
797
798 private unsetTaskStealing (): void {
19b8be8b 799 for (const workerNodeKey of this.workerNodes.keys()) {
e1c2dba7 800 this.workerNodes[workerNodeKey].off(
e44639e9
JB
801 'idle',
802 this.handleWorkerNodeIdleEvent
9f95d5eb 803 )
d6ca1416
JB
804 }
805 }
806
807 private setTasksStealingOnBackPressure (): void {
19b8be8b 808 for (const workerNodeKey of this.workerNodes.keys()) {
e1c2dba7 809 this.workerNodes[workerNodeKey].on(
b5e75be8 810 'backPressure',
e44639e9 811 this.handleWorkerNodeBackPressureEvent
9f95d5eb 812 )
d6ca1416
JB
813 }
814 }
815
816 private unsetTasksStealingOnBackPressure (): void {
19b8be8b 817 for (const workerNodeKey of this.workerNodes.keys()) {
e1c2dba7 818 this.workerNodes[workerNodeKey].off(
b5e75be8 819 'backPressure',
e44639e9 820 this.handleWorkerNodeBackPressureEvent
9f95d5eb 821 )
d6ca1416
JB
822 }
823 }
824
c319c66b
JB
825 /**
826 * Whether the pool is full or not.
827 *
828 * The pool filling boolean status.
829 */
dea903a8 830 protected get full (): boolean {
26ce26ca
JB
831 return (
832 this.workerNodes.length >=
833 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
834 )
dea903a8 835 }
c2ade475 836
c319c66b
JB
837 /**
838 * Whether the pool is busy or not.
839 *
840 * The pool busyness boolean status.
841 */
842 protected abstract get busy (): boolean
7c0ba920 843
6c6afb84 844 /**
3d76750a 845 * Whether worker nodes are executing concurrently their tasks quota or not.
6c6afb84
JB
846 *
847 * @returns Worker nodes busyness boolean status.
848 */
c2ade475 849 protected internalBusy (): boolean {
3d76750a
JB
850 if (this.opts.enableTasksQueue === true) {
851 return (
852 this.workerNodes.findIndex(
041dc05b 853 workerNode =>
3d76750a
JB
854 workerNode.info.ready &&
855 workerNode.usage.tasks.executing <
67f3f2d6
JB
856 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
857 this.opts.tasksQueueOptions!.concurrency!
3d76750a
JB
858 ) === -1
859 )
3d76750a 860 }
419e8121
JB
861 return (
862 this.workerNodes.findIndex(
863 workerNode =>
864 workerNode.info.ready && workerNode.usage.tasks.executing === 0
865 ) === -1
866 )
cb70b19d
JB
867 }
868
42c677c1
JB
869 private isWorkerNodeBusy (workerNodeKey: number): boolean {
870 if (this.opts.enableTasksQueue === true) {
871 return (
872 this.workerNodes[workerNodeKey].usage.tasks.executing >=
67f3f2d6
JB
873 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
874 this.opts.tasksQueueOptions!.concurrency!
42c677c1
JB
875 )
876 }
877 return this.workerNodes[workerNodeKey].usage.tasks.executing > 0
878 }
879
e81c38f2 880 private async sendTaskFunctionOperationToWorker (
72ae84a2
JB
881 workerNodeKey: number,
882 message: MessageValue<Data>
883 ): Promise<boolean> {
72ae84a2 884 return await new Promise<boolean>((resolve, reject) => {
ae036c3e
JB
885 const taskFunctionOperationListener = (
886 message: MessageValue<Response>
887 ): void => {
888 this.checkMessageWorkerId(message)
1851fed0 889 const workerId = this.getWorkerInfo(workerNodeKey)?.id
72ae84a2 890 if (
ae036c3e
JB
891 message.taskFunctionOperationStatus != null &&
892 message.workerId === workerId
72ae84a2 893 ) {
ae036c3e
JB
894 if (message.taskFunctionOperationStatus) {
895 resolve(true)
c63a35a0 896 } else {
ae036c3e
JB
897 reject(
898 new Error(
c63a35a0 899 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
ae036c3e 900 )
72ae84a2 901 )
ae036c3e
JB
902 }
903 this.deregisterWorkerMessageListener(
904 this.getWorkerNodeKeyByWorkerId(message.workerId),
905 taskFunctionOperationListener
72ae84a2
JB
906 )
907 }
ae036c3e
JB
908 }
909 this.registerWorkerMessageListener(
910 workerNodeKey,
911 taskFunctionOperationListener
912 )
72ae84a2
JB
913 this.sendToWorker(workerNodeKey, message)
914 })
915 }
916
917 private async sendTaskFunctionOperationToWorkers (
adee6053 918 message: MessageValue<Data>
e81c38f2
JB
919 ): Promise<boolean> {
920 return await new Promise<boolean>((resolve, reject) => {
ae036c3e
JB
921 const responsesReceived = new Array<MessageValue<Response>>()
922 const taskFunctionOperationsListener = (
923 message: MessageValue<Response>
924 ): void => {
925 this.checkMessageWorkerId(message)
926 if (message.taskFunctionOperationStatus != null) {
927 responsesReceived.push(message)
928 if (responsesReceived.length === this.workerNodes.length) {
e81c38f2 929 if (
e81c38f2
JB
930 responsesReceived.every(
931 message => message.taskFunctionOperationStatus === true
932 )
933 ) {
934 resolve(true)
935 } else if (
e81c38f2
JB
936 responsesReceived.some(
937 message => message.taskFunctionOperationStatus === false
938 )
939 ) {
b0b55f57
JB
940 const errorResponse = responsesReceived.find(
941 response => response.taskFunctionOperationStatus === false
942 )
e81c38f2
JB
943 reject(
944 new Error(
b0b55f57 945 `Task function operation '${
e81c38f2 946 message.taskFunctionOperation as string
c63a35a0
JB
947 }' failed on worker ${errorResponse?.workerId} with error: '${
948 errorResponse?.workerError?.message
b0b55f57 949 }'`
e81c38f2
JB
950 )
951 )
952 }
ae036c3e
JB
953 this.deregisterWorkerMessageListener(
954 this.getWorkerNodeKeyByWorkerId(message.workerId),
955 taskFunctionOperationsListener
956 )
e81c38f2 957 }
ae036c3e
JB
958 }
959 }
19b8be8b 960 for (const workerNodeKey of this.workerNodes.keys()) {
ae036c3e
JB
961 this.registerWorkerMessageListener(
962 workerNodeKey,
963 taskFunctionOperationsListener
964 )
72ae84a2 965 this.sendToWorker(workerNodeKey, message)
e81c38f2
JB
966 }
967 })
6703b9f4
JB
968 }
969
970 /** @inheritDoc */
971 public hasTaskFunction (name: string): boolean {
85bbc7ab
JB
972 return this.listTaskFunctionsProperties().some(
973 taskFunctionProperties => taskFunctionProperties.name === name
974 )
6703b9f4
JB
975 }
976
977 /** @inheritDoc */
e81c38f2
JB
978 public async addTaskFunction (
979 name: string,
31847469 980 fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>
e81c38f2 981 ): Promise<boolean> {
3feeab69
JB
982 if (typeof name !== 'string') {
983 throw new TypeError('name argument must be a string')
984 }
985 if (typeof name === 'string' && name.trim().length === 0) {
986 throw new TypeError('name argument must not be an empty string')
987 }
31847469
JB
988 if (typeof fn === 'function') {
989 fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response>
990 }
991 if (typeof fn.taskFunction !== 'function') {
992 throw new TypeError('taskFunction property must be a function')
3feeab69 993 }
95d1a734
JB
994 checkValidPriority(fn.priority)
995 checkValidWorkerChoiceStrategy(fn.strategy)
adee6053 996 const opResult = await this.sendTaskFunctionOperationToWorkers({
6703b9f4 997 taskFunctionOperation: 'add',
31847469
JB
998 taskFunctionProperties: buildTaskFunctionProperties(name, fn),
999 taskFunction: fn.taskFunction.toString()
6703b9f4 1000 })
adee6053 1001 this.taskFunctions.set(name, fn)
85bbc7ab 1002 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
91041638 1003 this.getWorkerChoiceStrategies()
85bbc7ab 1004 )
9a55fa8c
JB
1005 for (const workerNodeKey of this.workerNodes.keys()) {
1006 this.sendStatisticsMessageToWorker(workerNodeKey)
1007 }
adee6053 1008 return opResult
6703b9f4
JB
1009 }
1010
1011 /** @inheritDoc */
e81c38f2 1012 public async removeTaskFunction (name: string): Promise<boolean> {
9eae3c69
JB
1013 if (!this.taskFunctions.has(name)) {
1014 throw new Error(
16248b23 1015 'Cannot remove a task function not handled on the pool side'
9eae3c69
JB
1016 )
1017 }
adee6053 1018 const opResult = await this.sendTaskFunctionOperationToWorkers({
6703b9f4 1019 taskFunctionOperation: 'remove',
31847469
JB
1020 taskFunctionProperties: buildTaskFunctionProperties(
1021 name,
1022 this.taskFunctions.get(name)
1023 )
6703b9f4 1024 })
9a55fa8c
JB
1025 for (const workerNode of this.workerNodes) {
1026 workerNode.deleteTaskFunctionWorkerUsage(name)
1027 }
adee6053 1028 this.taskFunctions.delete(name)
85bbc7ab 1029 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
91041638 1030 this.getWorkerChoiceStrategies()
85bbc7ab 1031 )
9a55fa8c
JB
1032 for (const workerNodeKey of this.workerNodes.keys()) {
1033 this.sendStatisticsMessageToWorker(workerNodeKey)
1034 }
adee6053 1035 return opResult
6703b9f4
JB
1036 }
1037
90d7d101 1038 /** @inheritDoc */
31847469 1039 public listTaskFunctionsProperties (): TaskFunctionProperties[] {
f2dbbf95
JB
1040 for (const workerNode of this.workerNodes) {
1041 if (
31847469
JB
1042 Array.isArray(workerNode.info.taskFunctionsProperties) &&
1043 workerNode.info.taskFunctionsProperties.length > 0
f2dbbf95 1044 ) {
31847469 1045 return workerNode.info.taskFunctionsProperties
f2dbbf95 1046 }
90d7d101 1047 }
f2dbbf95 1048 return []
90d7d101
JB
1049 }
1050
bcfb06ce 1051 /**
91041638 1052 * Gets task function worker choice strategy, if any.
bcfb06ce
JB
1053 *
1054 * @param name - The task function name.
1055 * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1056 */
91041638 1057 private readonly getTaskFunctionWorkerChoiceStrategy = (
bcfb06ce
JB
1058 name?: string
1059 ): WorkerChoiceStrategy | undefined => {
91041638
JB
1060 name = name ?? DEFAULT_TASK_NAME
1061 const taskFunctionsProperties = this.listTaskFunctionsProperties()
1062 if (name === DEFAULT_TASK_NAME) {
1063 name = taskFunctionsProperties[1]?.name
bcfb06ce 1064 }
91041638
JB
1065 return taskFunctionsProperties.find(
1066 (taskFunctionProperties: TaskFunctionProperties) =>
1067 taskFunctionProperties.name === name
1068 )?.strategy
1069 }
1070
1071 /**
1072 * Gets worker node task function worker choice strategy, if any.
1073 *
1074 * @param workerNodeKey - The worker node key.
1075 * @param name - The task function name.
1076 * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1077 */
1078 private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy = (
1079 workerNodeKey: number,
1080 name?: string
1081 ): WorkerChoiceStrategy | undefined => {
1082 const workerInfo = this.getWorkerInfo(workerNodeKey)
1083 if (workerInfo == null) {
1084 return
1085 }
1086 name = name ?? DEFAULT_TASK_NAME
1087 if (name === DEFAULT_TASK_NAME) {
1088 name = workerInfo.taskFunctionsProperties?.[1]?.name
1089 }
1090 return workerInfo.taskFunctionsProperties?.find(
1091 (taskFunctionProperties: TaskFunctionProperties) =>
1092 taskFunctionProperties.name === name
1093 )?.strategy
bcfb06ce
JB
1094 }
1095
95d1a734
JB
1096 /**
1097 * Gets worker node task function priority, if any.
1098 *
1099 * @param workerNodeKey - The worker node key.
1100 * @param name - The task function name.
a20062fa 1101 * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
95d1a734
JB
1102 */
1103 private readonly getWorkerNodeTaskFunctionPriority = (
1104 workerNodeKey: number,
1105 name?: string
1106 ): number | undefined => {
91041638
JB
1107 const workerInfo = this.getWorkerInfo(workerNodeKey)
1108 if (workerInfo == null) {
1109 return
95d1a734 1110 }
91041638
JB
1111 name = name ?? DEFAULT_TASK_NAME
1112 if (name === DEFAULT_TASK_NAME) {
1113 name = workerInfo.taskFunctionsProperties?.[1]?.name
1114 }
1115 return workerInfo.taskFunctionsProperties?.find(
1116 (taskFunctionProperties: TaskFunctionProperties) =>
1117 taskFunctionProperties.name === name
1118 )?.priority
95d1a734
JB
1119 }
1120
85bbc7ab
JB
1121 /**
1122 * Gets the worker choice strategies registered in this pool.
1123 *
1124 * @returns The worker choice strategies.
1125 */
91041638 1126 private readonly getWorkerChoiceStrategies =
85bbc7ab
JB
1127 (): Set<WorkerChoiceStrategy> => {
1128 return new Set([
1129 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1130 this.opts.workerChoiceStrategy!,
1131 ...(this.listTaskFunctionsProperties()
1132 .map(
1133 (taskFunctionProperties: TaskFunctionProperties) =>
1134 taskFunctionProperties.strategy
1135 )
1136 .filter(
1137 (strategy: WorkerChoiceStrategy | undefined) => strategy != null
1138 ) as WorkerChoiceStrategy[])
1139 ])
1140 }
1141
6703b9f4 1142 /** @inheritDoc */
e81c38f2 1143 public async setDefaultTaskFunction (name: string): Promise<boolean> {
72ae84a2 1144 return await this.sendTaskFunctionOperationToWorkers({
6703b9f4 1145 taskFunctionOperation: 'default',
31847469
JB
1146 taskFunctionProperties: buildTaskFunctionProperties(
1147 name,
1148 this.taskFunctions.get(name)
1149 )
6703b9f4 1150 })
6703b9f4
JB
1151 }
1152
375f7504
JB
1153 private shallExecuteTask (workerNodeKey: number): boolean {
1154 return (
1155 this.tasksQueueSize(workerNodeKey) === 0 &&
1156 this.workerNodes[workerNodeKey].usage.tasks.executing <
67f3f2d6
JB
1157 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1158 this.opts.tasksQueueOptions!.concurrency!
375f7504
JB
1159 )
1160 }
1161
afc003b2 1162 /** @inheritDoc */
7d91a8cd
JB
1163 public async execute (
1164 data?: Data,
1165 name?: string,
6a3ecc50 1166 transferList?: readonly TransferListItem[]
7d91a8cd 1167 ): Promise<Response> {
52b71763 1168 return await new Promise<Response>((resolve, reject) => {
15b176e0 1169 if (!this.started) {
47352846 1170 reject(new Error('Cannot execute a task on not started pool'))
9d2d0da1 1171 return
15b176e0 1172 }
711623b8
JB
1173 if (this.destroying) {
1174 reject(new Error('Cannot execute a task on destroying pool'))
1175 return
1176 }
7d91a8cd
JB
1177 if (name != null && typeof name !== 'string') {
1178 reject(new TypeError('name argument must be a string'))
9d2d0da1 1179 return
7d91a8cd 1180 }
90d7d101
JB
1181 if (
1182 name != null &&
1183 typeof name === 'string' &&
1184 name.trim().length === 0
1185 ) {
f58b60b9 1186 reject(new TypeError('name argument must not be an empty string'))
9d2d0da1 1187 return
90d7d101 1188 }
b558f6b5
JB
1189 if (transferList != null && !Array.isArray(transferList)) {
1190 reject(new TypeError('transferList argument must be an array'))
9d2d0da1 1191 return
b558f6b5
JB
1192 }
1193 const timestamp = performance.now()
91041638 1194 const workerNodeKey = this.chooseWorkerNode(name)
501aea93 1195 const task: Task<Data> = {
52b71763
JB
1196 name: name ?? DEFAULT_TASK_NAME,
1197 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1198 data: data ?? ({} as Data),
95d1a734 1199 priority: this.getWorkerNodeTaskFunctionPriority(workerNodeKey, name),
91041638
JB
1200 strategy: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy(
1201 workerNodeKey,
1202 name
1203 ),
7d91a8cd 1204 transferList,
52b71763 1205 timestamp,
7629bdf1 1206 taskId: randomUUID()
52b71763 1207 }
67f3f2d6
JB
1208 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1209 this.promiseResponseMap.set(task.taskId!, {
2e81254d
JB
1210 resolve,
1211 reject,
f18fd12b
JB
1212 workerNodeKey,
1213 ...(this.emitter != null && {
1214 asyncResource: new AsyncResource('poolifier:task', {
1215 triggerAsyncId: this.emitter.asyncId,
1216 requireManualDestroy: true
1217 })
1218 })
2e81254d 1219 })
52b71763 1220 if (
4e377863
JB
1221 this.opts.enableTasksQueue === false ||
1222 (this.opts.enableTasksQueue === true &&
375f7504 1223 this.shallExecuteTask(workerNodeKey))
52b71763 1224 ) {
501aea93 1225 this.executeTask(workerNodeKey, task)
4e377863
JB
1226 } else {
1227 this.enqueueTask(workerNodeKey, task)
52b71763 1228 }
2e81254d 1229 })
280c2a77 1230 }
c97c7edb 1231
60dc0a9c
JB
1232 /**
1233 * Starts the minimum number of workers.
1234 */
e0843544 1235 private startMinimumNumberOfWorkers (initWorkerNodeUsage = false): void {
b362a929 1236 this.startingMinimumNumberOfWorkers = true
60dc0a9c
JB
1237 while (
1238 this.workerNodes.reduce(
1239 (accumulator, workerNode) =>
1240 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
1241 0
1242 ) < this.minimumNumberOfWorkers
1243 ) {
e0843544
JB
1244 const workerNodeKey = this.createAndSetupWorkerNode()
1245 initWorkerNodeUsage &&
1246 this.initWorkerNodeUsage(this.workerNodes[workerNodeKey])
60dc0a9c 1247 }
b362a929 1248 this.startingMinimumNumberOfWorkers = false
60dc0a9c
JB
1249 }
1250
47352846
JB
1251 /** @inheritdoc */
1252 public start (): void {
711623b8
JB
1253 if (this.started) {
1254 throw new Error('Cannot start an already started pool')
1255 }
1256 if (this.starting) {
1257 throw new Error('Cannot start an already starting pool')
1258 }
1259 if (this.destroying) {
1260 throw new Error('Cannot start a destroying pool')
1261 }
47352846 1262 this.starting = true
60dc0a9c 1263 this.startMinimumNumberOfWorkers()
2008bccd 1264 this.startTimestamp = performance.now()
47352846
JB
1265 this.starting = false
1266 this.started = true
1267 }
1268
afc003b2 1269 /** @inheritDoc */
c97c7edb 1270 public async destroy (): Promise<void> {
711623b8
JB
1271 if (!this.started) {
1272 throw new Error('Cannot destroy an already destroyed pool')
1273 }
1274 if (this.starting) {
1275 throw new Error('Cannot destroy an starting pool')
1276 }
1277 if (this.destroying) {
1278 throw new Error('Cannot destroy an already destroying pool')
1279 }
1280 this.destroying = true
1fbcaa7c 1281 await Promise.all(
533a8e22 1282 this.workerNodes.map(async (_, workerNodeKey) => {
aa9eede8 1283 await this.destroyWorkerNode(workerNodeKey)
1fbcaa7c
JB
1284 })
1285 )
33e6bb4c 1286 this.emitter?.emit(PoolEvents.destroy, this.info)
f80125ca 1287 this.emitter?.emitDestroy()
55082af9 1288 this.readyEventEmitted = false
2008bccd 1289 delete this.startTimestamp
711623b8 1290 this.destroying = false
15b176e0 1291 this.started = false
c97c7edb
S
1292 }
1293
26ce26ca 1294 private async sendKillMessageToWorker (workerNodeKey: number): Promise<void> {
9edb9717 1295 await new Promise<void>((resolve, reject) => {
c63a35a0
JB
1296 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1297 if (this.workerNodes[workerNodeKey] == null) {
ad3836ed 1298 resolve()
85b2561d
JB
1299 return
1300 }
ae036c3e
JB
1301 const killMessageListener = (message: MessageValue<Response>): void => {
1302 this.checkMessageWorkerId(message)
1e3214b6
JB
1303 if (message.kill === 'success') {
1304 resolve()
1305 } else if (message.kill === 'failure') {
72ae84a2
JB
1306 reject(
1307 new Error(
c63a35a0 1308 `Kill message handling failed on worker ${message.workerId}`
72ae84a2
JB
1309 )
1310 )
1e3214b6 1311 }
ae036c3e 1312 }
51d9cfbd 1313 // FIXME: should be registered only once
ae036c3e 1314 this.registerWorkerMessageListener(workerNodeKey, killMessageListener)
72ae84a2 1315 this.sendToWorker(workerNodeKey, { kill: true })
1e3214b6 1316 })
1e3214b6
JB
1317 }
1318
4a6952ff 1319 /**
aa9eede8 1320 * Terminates the worker node given its worker node key.
4a6952ff 1321 *
aa9eede8 1322 * @param workerNodeKey - The worker node key.
4a6952ff 1323 */
07e0c9e5
JB
1324 protected async destroyWorkerNode (workerNodeKey: number): Promise<void> {
1325 this.flagWorkerNodeAsNotReady(workerNodeKey)
87347ea8 1326 const flushedTasks = this.flushTasksQueue(workerNodeKey)
07e0c9e5 1327 const workerNode = this.workerNodes[workerNodeKey]
32b141fd
JB
1328 await waitWorkerNodeEvents(
1329 workerNode,
1330 'taskFinished',
1331 flushedTasks,
1332 this.opts.tasksQueueOptions?.tasksFinishedTimeout ??
26ce26ca
JB
1333 getDefaultTasksQueueOptions(
1334 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
1335 ).tasksFinishedTimeout
32b141fd 1336 )
07e0c9e5
JB
1337 await this.sendKillMessageToWorker(workerNodeKey)
1338 await workerNode.terminate()
1339 }
c97c7edb 1340
729c563d 1341 /**
6677a3d3
JB
1342 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1343 * Can be overridden.
afc003b2
JB
1344 *
1345 * @virtual
729c563d 1346 */
280c2a77 1347 protected setupHook (): void {
965df41c 1348 /* Intentionally empty */
280c2a77 1349 }
c97c7edb 1350
729c563d 1351 /**
5bec72fd
JB
1352 * Returns whether the worker is the main worker or not.
1353 *
1354 * @returns `true` if the worker is the main worker, `false` otherwise.
280c2a77
S
1355 */
1356 protected abstract isMain (): boolean
1357
1358 /**
2e81254d 1359 * Hook executed before the worker task execution.
bf9549ae 1360 * Can be overridden.
729c563d 1361 *
f06e48d8 1362 * @param workerNodeKey - The worker node key.
1c6fe997 1363 * @param task - The task to execute.
729c563d 1364 */
1c6fe997
JB
1365 protected beforeTaskExecutionHook (
1366 workerNodeKey: number,
1367 task: Task<Data>
1368 ): void {
c63a35a0 1369 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
efabc98d 1370 if (this.workerNodes[workerNodeKey]?.usage != null) {
94407def
JB
1371 const workerUsage = this.workerNodes[workerNodeKey].usage
1372 ++workerUsage.tasks.executing
c329fd41 1373 updateWaitTimeWorkerUsage(
bcfb06ce 1374 this.workerChoiceStrategiesContext,
c329fd41
JB
1375 workerUsage,
1376 task
1377 )
94407def
JB
1378 }
1379 if (
1380 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
67f3f2d6
JB
1381 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1382 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(task.name!) !=
1383 null
94407def 1384 ) {
67f3f2d6 1385 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
db0e38ee 1386 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 1387 workerNodeKey
67f3f2d6
JB
1388 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1389 ].getTaskFunctionWorkerUsage(task.name!)!
5623b8d5 1390 ++taskFunctionWorkerUsage.tasks.executing
c329fd41 1391 updateWaitTimeWorkerUsage(
bcfb06ce 1392 this.workerChoiceStrategiesContext,
c329fd41
JB
1393 taskFunctionWorkerUsage,
1394 task
1395 )
b558f6b5 1396 }
c97c7edb
S
1397 }
1398
c01733f1 1399 /**
2e81254d 1400 * Hook executed after the worker task execution.
bf9549ae 1401 * Can be overridden.
c01733f1 1402 *
501aea93 1403 * @param workerNodeKey - The worker node key.
38e795c1 1404 * @param message - The received message.
c01733f1 1405 */
2e81254d 1406 protected afterTaskExecutionHook (
501aea93 1407 workerNodeKey: number,
2740a743 1408 message: MessageValue<Response>
bf9549ae 1409 ): void {
9a55fa8c 1410 let needWorkerChoiceStrategiesUpdate = false
c63a35a0 1411 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
efabc98d 1412 if (this.workerNodes[workerNodeKey]?.usage != null) {
94407def 1413 const workerUsage = this.workerNodes[workerNodeKey].usage
c329fd41
JB
1414 updateTaskStatisticsWorkerUsage(workerUsage, message)
1415 updateRunTimeWorkerUsage(
bcfb06ce 1416 this.workerChoiceStrategiesContext,
c329fd41
JB
1417 workerUsage,
1418 message
1419 )
1420 updateEluWorkerUsage(
bcfb06ce 1421 this.workerChoiceStrategiesContext,
c329fd41
JB
1422 workerUsage,
1423 message
1424 )
9a55fa8c 1425 needWorkerChoiceStrategiesUpdate = true
94407def
JB
1426 }
1427 if (
1428 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1429 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
67f3f2d6
JB
1430 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1431 message.taskPerformance!.name
94407def
JB
1432 ) != null
1433 ) {
67f3f2d6 1434 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
db0e38ee 1435 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 1436 workerNodeKey
67f3f2d6
JB
1437 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1438 ].getTaskFunctionWorkerUsage(message.taskPerformance!.name)!
c329fd41
JB
1439 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
1440 updateRunTimeWorkerUsage(
bcfb06ce 1441 this.workerChoiceStrategiesContext,
c329fd41
JB
1442 taskFunctionWorkerUsage,
1443 message
1444 )
1445 updateEluWorkerUsage(
bcfb06ce 1446 this.workerChoiceStrategiesContext,
c329fd41
JB
1447 taskFunctionWorkerUsage,
1448 message
1449 )
9a55fa8c 1450 needWorkerChoiceStrategiesUpdate = true
c329fd41 1451 }
9a55fa8c 1452 if (needWorkerChoiceStrategiesUpdate) {
bcfb06ce 1453 this.workerChoiceStrategiesContext?.update(workerNodeKey)
b558f6b5
JB
1454 }
1455 }
1456
db0e38ee
JB
1457 /**
1458 * Whether the worker node shall update its task function worker usage or not.
1459 *
1460 * @param workerNodeKey - The worker node key.
1461 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1462 */
1463 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
a5d15204 1464 const workerInfo = this.getWorkerInfo(workerNodeKey)
b558f6b5 1465 return (
1851fed0 1466 workerInfo != null &&
31847469
JB
1467 Array.isArray(workerInfo.taskFunctionsProperties) &&
1468 workerInfo.taskFunctionsProperties.length > 2
b558f6b5 1469 )
f1c06930
JB
1470 }
1471
280c2a77 1472 /**
91041638 1473 * Chooses a worker node for the next task.
280c2a77 1474 *
91041638 1475 * @param name - The task function name.
db89e3bc 1476 * @returns The chosen worker node key.
280c2a77 1477 */
91041638 1478 private chooseWorkerNode (name?: string): number {
930dcf12 1479 if (this.shallCreateDynamicWorker()) {
aa9eede8 1480 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
6c6afb84 1481 if (
bcfb06ce
JB
1482 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage ===
1483 true
6c6afb84 1484 ) {
aa9eede8 1485 return workerNodeKey
6c6afb84 1486 }
17393ac8 1487 }
c63a35a0 1488 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
91041638
JB
1489 return this.workerChoiceStrategiesContext!.execute(
1490 this.getTaskFunctionWorkerChoiceStrategy(name)
1491 )
930dcf12
JB
1492 }
1493
6c6afb84
JB
1494 /**
1495 * Conditions for dynamic worker creation.
1496 *
1497 * @returns Whether to create a dynamic worker or not.
1498 */
9d9fb7b6 1499 protected abstract shallCreateDynamicWorker (): boolean
c97c7edb 1500
280c2a77 1501 /**
aa9eede8 1502 * Sends a message to worker given its worker node key.
280c2a77 1503 *
aa9eede8 1504 * @param workerNodeKey - The worker node key.
38e795c1 1505 * @param message - The message.
7d91a8cd 1506 * @param transferList - The optional array of transferable objects.
280c2a77
S
1507 */
1508 protected abstract sendToWorker (
aa9eede8 1509 workerNodeKey: number,
7d91a8cd 1510 message: MessageValue<Data>,
6a3ecc50 1511 transferList?: readonly TransferListItem[]
280c2a77
S
1512 ): void
1513
e0843544
JB
1514 /**
1515 * Initializes the worker node usage with sensible default values gathered during runtime.
1516 *
1517 * @param workerNode - The worker node.
1518 */
1519 private initWorkerNodeUsage (workerNode: IWorkerNode<Worker, Data>): void {
1520 if (
1521 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1522 .runTime.aggregate === true
1523 ) {
1524 workerNode.usage.runTime.aggregate = min(
1525 ...this.workerNodes.map(
80115618
JB
1526 workerNode =>
1527 workerNode.usage.runTime.aggregate ?? Number.POSITIVE_INFINITY
e0843544
JB
1528 )
1529 )
1530 }
1531 if (
1532 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1533 .waitTime.aggregate === true
1534 ) {
1535 workerNode.usage.waitTime.aggregate = min(
1536 ...this.workerNodes.map(
80115618
JB
1537 workerNode =>
1538 workerNode.usage.waitTime.aggregate ?? Number.POSITIVE_INFINITY
e0843544
JB
1539 )
1540 )
1541 }
1542 if (
1543 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu
1544 .aggregate === true
1545 ) {
1546 workerNode.usage.elu.active.aggregate = min(
1547 ...this.workerNodes.map(
80115618
JB
1548 workerNode =>
1549 workerNode.usage.elu.active.aggregate ?? Number.POSITIVE_INFINITY
e0843544
JB
1550 )
1551 )
1552 }
1553 }
1554
4a6952ff 1555 /**
aa9eede8 1556 * Creates a new, completely set up worker node.
4a6952ff 1557 *
aa9eede8 1558 * @returns New, completely set up worker node key.
4a6952ff 1559 */
aa9eede8 1560 protected createAndSetupWorkerNode (): number {
c3719753
JB
1561 const workerNode = this.createWorkerNode()
1562 workerNode.registerWorkerEventHandler(
1563 'online',
1564 this.opts.onlineHandler ?? EMPTY_FUNCTION
1565 )
1566 workerNode.registerWorkerEventHandler(
1567 'message',
1568 this.opts.messageHandler ?? EMPTY_FUNCTION
1569 )
1570 workerNode.registerWorkerEventHandler(
1571 'error',
1572 this.opts.errorHandler ?? EMPTY_FUNCTION
1573 )
b271fce0 1574 workerNode.registerOnceWorkerEventHandler('error', (error: Error) => {
07e0c9e5 1575 workerNode.info.ready = false
2a69b8c5 1576 this.emitter?.emit(PoolEvents.error, error)
15b176e0 1577 if (
b6bfca01 1578 this.started &&
711623b8 1579 !this.destroying &&
9b38ab2d 1580 this.opts.restartWorkerOnError === true
15b176e0 1581 ) {
07e0c9e5 1582 if (workerNode.info.dynamic) {
aa9eede8 1583 this.createAndSetupDynamicWorkerNode()
b362a929 1584 } else if (!this.startingMinimumNumberOfWorkers) {
e0843544 1585 this.startMinimumNumberOfWorkers(true)
8a1260a3 1586 }
5baee0d7 1587 }
3c9123c7
JB
1588 if (
1589 this.started &&
1590 !this.destroying &&
1591 this.opts.enableTasksQueue === true
1592 ) {
9974369e 1593 this.redistributeQueuedTasks(this.workerNodes.indexOf(workerNode))
19dbc45b 1594 }
b4f8aca8 1595 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
07f6f7b1 1596 workerNode?.terminate().catch((error: unknown) => {
07e0c9e5
JB
1597 this.emitter?.emit(PoolEvents.error, error)
1598 })
5baee0d7 1599 })
c3719753
JB
1600 workerNode.registerWorkerEventHandler(
1601 'exit',
1602 this.opts.exitHandler ?? EMPTY_FUNCTION
1603 )
1604 workerNode.registerOnceWorkerEventHandler('exit', () => {
9974369e 1605 this.removeWorkerNode(workerNode)
b362a929
JB
1606 if (
1607 this.started &&
1608 !this.startingMinimumNumberOfWorkers &&
1609 !this.destroying
1610 ) {
e0843544 1611 this.startMinimumNumberOfWorkers(true)
60dc0a9c 1612 }
a974afa6 1613 })
c3719753 1614 const workerNodeKey = this.addWorkerNode(workerNode)
aa9eede8 1615 this.afterWorkerNodeSetup(workerNodeKey)
aa9eede8 1616 return workerNodeKey
c97c7edb 1617 }
be0676b3 1618
930dcf12 1619 /**
aa9eede8 1620 * Creates a new, completely set up dynamic worker node.
930dcf12 1621 *
aa9eede8 1622 * @returns New, completely set up dynamic worker node key.
930dcf12 1623 */
aa9eede8
JB
1624 protected createAndSetupDynamicWorkerNode (): number {
1625 const workerNodeKey = this.createAndSetupWorkerNode()
041dc05b 1626 this.registerWorkerMessageListener(workerNodeKey, message => {
4d159167 1627 this.checkMessageWorkerId(message)
aa9eede8
JB
1628 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
1629 message.workerId
aad6fb64 1630 )
152e87a8 1631 const workerInfo = this.getWorkerInfo(localWorkerNodeKey)
2b6b412f 1632 const workerUsage = this.workerNodes[localWorkerNodeKey]?.usage
81c02522 1633 // Kill message received from worker
930dcf12
JB
1634 if (
1635 isKillBehavior(KillBehaviors.HARD, message.kill) ||
1e3214b6 1636 (isKillBehavior(KillBehaviors.SOFT, message.kill) &&
7b56f532 1637 ((this.opts.enableTasksQueue === false &&
aa9eede8 1638 workerUsage.tasks.executing === 0) ||
7b56f532 1639 (this.opts.enableTasksQueue === true &&
152e87a8
JB
1640 workerInfo != null &&
1641 !workerInfo.stealing &&
aa9eede8
JB
1642 workerUsage.tasks.executing === 0 &&
1643 this.tasksQueueSize(localWorkerNodeKey) === 0)))
930dcf12 1644 ) {
f3827d5d 1645 // Flag the worker node as not ready immediately
ae3ab61d 1646 this.flagWorkerNodeAsNotReady(localWorkerNodeKey)
07f6f7b1 1647 this.destroyWorkerNode(localWorkerNodeKey).catch((error: unknown) => {
5270d253
JB
1648 this.emitter?.emit(PoolEvents.error, error)
1649 })
930dcf12
JB
1650 }
1651 })
aa9eede8 1652 this.sendToWorker(workerNodeKey, {
e9dd5b66 1653 checkActive: true
21f710aa 1654 })
72ae84a2 1655 if (this.taskFunctions.size > 0) {
31847469 1656 for (const [taskFunctionName, taskFunctionObject] of this.taskFunctions) {
72ae84a2
JB
1657 this.sendTaskFunctionOperationToWorker(workerNodeKey, {
1658 taskFunctionOperation: 'add',
31847469
JB
1659 taskFunctionProperties: buildTaskFunctionProperties(
1660 taskFunctionName,
1661 taskFunctionObject
1662 ),
1663 taskFunction: taskFunctionObject.taskFunction.toString()
07f6f7b1 1664 }).catch((error: unknown) => {
72ae84a2
JB
1665 this.emitter?.emit(PoolEvents.error, error)
1666 })
1667 }
1668 }
e44639e9
JB
1669 const workerNode = this.workerNodes[workerNodeKey]
1670 workerNode.info.dynamic = true
b1aae695 1671 if (
bcfb06ce
JB
1672 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerReady ===
1673 true ||
1674 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage ===
1675 true
b1aae695 1676 ) {
e44639e9 1677 workerNode.info.ready = true
b5e113f6 1678 }
e0843544 1679 this.initWorkerNodeUsage(workerNode)
33e6bb4c 1680 this.checkAndEmitDynamicWorkerCreationEvents()
aa9eede8 1681 return workerNodeKey
930dcf12
JB
1682 }
1683
a2ed5053 1684 /**
aa9eede8 1685 * Registers a listener callback on the worker given its worker node key.
a2ed5053 1686 *
aa9eede8 1687 * @param workerNodeKey - The worker node key.
a2ed5053
JB
1688 * @param listener - The message listener callback.
1689 */
85aeb3f3
JB
1690 protected abstract registerWorkerMessageListener<
1691 Message extends Data | Response
aa9eede8
JB
1692 >(
1693 workerNodeKey: number,
1694 listener: (message: MessageValue<Message>) => void
1695 ): void
a2ed5053 1696
ae036c3e
JB
1697 /**
1698 * Registers once a listener callback on the worker given its worker node key.
1699 *
1700 * @param workerNodeKey - The worker node key.
1701 * @param listener - The message listener callback.
1702 */
1703 protected abstract registerOnceWorkerMessageListener<
1704 Message extends Data | Response
1705 >(
1706 workerNodeKey: number,
1707 listener: (message: MessageValue<Message>) => void
1708 ): void
1709
1710 /**
1711 * Deregisters a listener callback on the worker given its worker node key.
1712 *
1713 * @param workerNodeKey - The worker node key.
1714 * @param listener - The message listener callback.
1715 */
1716 protected abstract deregisterWorkerMessageListener<
1717 Message extends Data | Response
1718 >(
1719 workerNodeKey: number,
1720 listener: (message: MessageValue<Message>) => void
1721 ): void
1722
a2ed5053 1723 /**
aa9eede8 1724 * Method hooked up after a worker node has been newly created.
a2ed5053
JB
1725 * Can be overridden.
1726 *
aa9eede8 1727 * @param workerNodeKey - The newly created worker node key.
a2ed5053 1728 */
aa9eede8 1729 protected afterWorkerNodeSetup (workerNodeKey: number): void {
a2ed5053 1730 // Listen to worker messages.
fcd39179
JB
1731 this.registerWorkerMessageListener(
1732 workerNodeKey,
3a776b6d 1733 this.workerMessageListener
fcd39179 1734 )
85aeb3f3 1735 // Send the startup message to worker.
aa9eede8 1736 this.sendStartupMessageToWorker(workerNodeKey)
9edb9717
JB
1737 // Send the statistics message to worker.
1738 this.sendStatisticsMessageToWorker(workerNodeKey)
72695f86 1739 if (this.opts.enableTasksQueue === true) {
dbd73092 1740 if (this.opts.tasksQueueOptions?.taskStealing === true) {
e1c2dba7 1741 this.workerNodes[workerNodeKey].on(
e44639e9
JB
1742 'idle',
1743 this.handleWorkerNodeIdleEvent
9f95d5eb 1744 )
47352846
JB
1745 }
1746 if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) {
e1c2dba7 1747 this.workerNodes[workerNodeKey].on(
b5e75be8 1748 'backPressure',
e44639e9 1749 this.handleWorkerNodeBackPressureEvent
9f95d5eb 1750 )
47352846 1751 }
72695f86 1752 }
d2c73f82
JB
1753 }
1754
85aeb3f3 1755 /**
aa9eede8
JB
1756 * Sends the startup message to worker given its worker node key.
1757 *
1758 * @param workerNodeKey - The worker node key.
1759 */
1760 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
1761
1762 /**
9edb9717 1763 * Sends the statistics message to worker given its worker node key.
85aeb3f3 1764 *
aa9eede8 1765 * @param workerNodeKey - The worker node key.
85aeb3f3 1766 */
9edb9717 1767 private sendStatisticsMessageToWorker (workerNodeKey: number): void {
aa9eede8
JB
1768 this.sendToWorker(workerNodeKey, {
1769 statistics: {
1770 runTime:
bcfb06ce 1771 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
f4d0a470 1772 .runTime.aggregate ?? false,
c63a35a0 1773 elu:
bcfb06ce
JB
1774 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1775 .elu.aggregate ?? false
72ae84a2 1776 }
aa9eede8
JB
1777 })
1778 }
a2ed5053 1779
5eb72b9e
JB
1780 private cannotStealTask (): boolean {
1781 return this.workerNodes.length <= 1 || this.info.queuedTasks === 0
1782 }
1783
42c677c1
JB
1784 private handleTask (workerNodeKey: number, task: Task<Data>): void {
1785 if (this.shallExecuteTask(workerNodeKey)) {
1786 this.executeTask(workerNodeKey, task)
1787 } else {
1788 this.enqueueTask(workerNodeKey, task)
1789 }
1790 }
1791
2d1d3b2d
JB
1792 private redistributeQueuedTasks (sourceWorkerNodeKey: number): void {
1793 if (sourceWorkerNodeKey === -1 || this.cannotStealTask()) {
cb71d660
JB
1794 return
1795 }
2d1d3b2d 1796 while (this.tasksQueueSize(sourceWorkerNodeKey) > 0) {
f201a0cd
JB
1797 const destinationWorkerNodeKey = this.workerNodes.reduce(
1798 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
2d1d3b2d
JB
1799 return sourceWorkerNodeKey !== workerNodeKey &&
1800 workerNode.info.ready &&
852ed3e4
JB
1801 workerNode.usage.tasks.queued <
1802 workerNodes[minWorkerNodeKey].usage.tasks.queued
f201a0cd
JB
1803 ? workerNodeKey
1804 : minWorkerNodeKey
1805 },
1806 0
1807 )
42c677c1
JB
1808 this.handleTask(
1809 destinationWorkerNodeKey,
67f3f2d6 1810 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2d1d3b2d 1811 this.dequeueTask(sourceWorkerNodeKey)!
42c677c1 1812 )
dd951876
JB
1813 }
1814 }
1815
b1838604
JB
1816 private updateTaskStolenStatisticsWorkerUsage (
1817 workerNodeKey: number,
b1838604
JB
1818 taskName: string
1819 ): void {
1a880eca 1820 const workerNode = this.workerNodes[workerNodeKey]
c63a35a0 1821 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
efabc98d 1822 if (workerNode?.usage != null) {
b1838604
JB
1823 ++workerNode.usage.tasks.stolen
1824 }
1825 if (
1826 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1827 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1828 ) {
8bd0556f
JB
1829 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1830 ++workerNode.getTaskFunctionWorkerUsage(taskName)!.tasks.stolen
b1838604
JB
1831 }
1832 }
1833
463226a4 1834 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
2d1d3b2d
JB
1835 workerNodeKey: number,
1836 taskName: string,
8bd0556f 1837 previousTaskName?: string
463226a4
JB
1838 ): void {
1839 const workerNode = this.workerNodes[workerNodeKey]
c63a35a0 1840 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
7aa2f476 1841 if (workerNode?.usage != null) {
463226a4
JB
1842 ++workerNode.usage.tasks.sequentiallyStolen
1843 }
1844 if (
1845 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
3b33cd2a
JB
1846 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1847 ) {
1848 const taskFunctionWorkerUsage =
1849 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1850 workerNode.getTaskFunctionWorkerUsage(taskName)!
1851 if (
1852 taskFunctionWorkerUsage.tasks.sequentiallyStolen === 0 ||
8bd0556f
JB
1853 (previousTaskName != null &&
1854 previousTaskName === taskName &&
3b33cd2a
JB
1855 taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0)
1856 ) {
1857 ++taskFunctionWorkerUsage.tasks.sequentiallyStolen
1858 } else if (taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) {
1859 taskFunctionWorkerUsage.tasks.sequentiallyStolen = 0
1860 }
463226a4
JB
1861 }
1862 }
1863
1864 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
2d1d3b2d
JB
1865 workerNodeKey: number,
1866 taskName: string
463226a4
JB
1867 ): void {
1868 const workerNode = this.workerNodes[workerNodeKey]
c63a35a0 1869 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
efabc98d 1870 if (workerNode?.usage != null) {
463226a4
JB
1871 workerNode.usage.tasks.sequentiallyStolen = 0
1872 }
1873 if (
1874 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1875 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1876 ) {
8bd0556f
JB
1877 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1878 workerNode.getTaskFunctionWorkerUsage(
1879 taskName
1880 )!.tasks.sequentiallyStolen = 0
463226a4
JB
1881 }
1882 }
1883
e44639e9 1884 private readonly handleWorkerNodeIdleEvent = (
e1c2dba7 1885 eventDetail: WorkerNodeEventDetail,
463226a4 1886 previousStolenTask?: Task<Data>
9f95d5eb 1887 ): void => {
e1c2dba7 1888 const { workerNodeKey } = eventDetail
463226a4
JB
1889 if (workerNodeKey == null) {
1890 throw new Error(
c63a35a0 1891 "WorkerNode event detail 'workerNodeKey' property must be defined"
463226a4
JB
1892 )
1893 }
c63a35a0 1894 const workerInfo = this.getWorkerInfo(workerNodeKey)
010f158c
JB
1895 if (workerInfo == null) {
1896 throw new Error(
1897 `Worker node with key '${workerNodeKey}' not found in pool`
1898 )
1899 }
5eb72b9e
JB
1900 if (
1901 this.cannotStealTask() ||
c63a35a0
JB
1902 (this.info.stealingWorkerNodes ?? 0) >
1903 Math.floor(this.workerNodes.length / 2)
5eb72b9e 1904 ) {
010f158c 1905 if (previousStolenTask != null) {
c63a35a0 1906 workerInfo.stealing = false
2d1d3b2d
JB
1907 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1908 workerNodeKey,
1909 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1910 previousStolenTask.name!
1911 )
5eb72b9e
JB
1912 }
1913 return
1914 }
463226a4
JB
1915 const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks
1916 if (
1917 previousStolenTask != null &&
463226a4
JB
1918 (workerNodeTasksUsage.executing > 0 ||
1919 this.tasksQueueSize(workerNodeKey) > 0)
1920 ) {
c63a35a0 1921 workerInfo.stealing = false
2d1d3b2d
JB
1922 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1923 workerNodeKey,
1924 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1925 previousStolenTask.name!
1926 )
463226a4
JB
1927 return
1928 }
c63a35a0 1929 workerInfo.stealing = true
463226a4 1930 const stolenTask = this.workerNodeStealTask(workerNodeKey)
8bd0556f 1931 if (stolenTask != null) {
2d1d3b2d
JB
1932 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(
1933 workerNodeKey,
67f3f2d6 1934 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2d1d3b2d 1935 stolenTask.name!,
8bd0556f 1936 previousStolenTask?.name
2d1d3b2d 1937 )
f1f77f45 1938 }
463226a4
JB
1939 sleep(exponentialDelay(workerNodeTasksUsage.sequentiallyStolen))
1940 .then(() => {
e44639e9 1941 this.handleWorkerNodeIdleEvent(eventDetail, stolenTask)
463226a4
JB
1942 return undefined
1943 })
07f6f7b1 1944 .catch((error: unknown) => {
2e8cfbb7
JB
1945 this.emitter?.emit(PoolEvents.error, error)
1946 })
463226a4
JB
1947 }
1948
1949 private readonly workerNodeStealTask = (
1950 workerNodeKey: number
1951 ): Task<Data> | undefined => {
dd951876 1952 const workerNodes = this.workerNodes
a6b3272b 1953 .slice()
dd951876
JB
1954 .sort(
1955 (workerNodeA, workerNodeB) =>
1956 workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
1957 )
f201a0cd 1958 const sourceWorkerNode = workerNodes.find(
463226a4
JB
1959 (sourceWorkerNode, sourceWorkerNodeKey) =>
1960 sourceWorkerNode.info.ready &&
5eb72b9e 1961 !sourceWorkerNode.info.stealing &&
463226a4
JB
1962 sourceWorkerNodeKey !== workerNodeKey &&
1963 sourceWorkerNode.usage.tasks.queued > 0
f201a0cd
JB
1964 )
1965 if (sourceWorkerNode != null) {
67f3f2d6 1966 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2eee7220 1967 const task = sourceWorkerNode.dequeueLastPrioritizedTask()!
42c677c1 1968 this.handleTask(workerNodeKey, task)
67f3f2d6
JB
1969 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1970 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!)
463226a4 1971 return task
72695f86
JB
1972 }
1973 }
1974
e44639e9 1975 private readonly handleWorkerNodeBackPressureEvent = (
e1c2dba7 1976 eventDetail: WorkerNodeEventDetail
9f95d5eb 1977 ): void => {
5eb72b9e
JB
1978 if (
1979 this.cannotStealTask() ||
2eee7220 1980 this.hasBackPressure() ||
c63a35a0
JB
1981 (this.info.stealingWorkerNodes ?? 0) >
1982 Math.floor(this.workerNodes.length / 2)
5eb72b9e 1983 ) {
cb71d660
JB
1984 return
1985 }
f778c355 1986 const sizeOffset = 1
67f3f2d6
JB
1987 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1988 if (this.opts.tasksQueueOptions!.size! <= sizeOffset) {
68dbcdc0
JB
1989 return
1990 }
7b2c5627 1991 const { workerId } = eventDetail
72695f86 1992 const sourceWorkerNode =
b5e75be8 1993 this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
72695f86 1994 const workerNodes = this.workerNodes
a6b3272b 1995 .slice()
72695f86
JB
1996 .sort(
1997 (workerNodeA, workerNodeB) =>
1998 workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
1999 )
2000 for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
2001 if (
0bc68267 2002 sourceWorkerNode.usage.tasks.queued > 0 &&
a6b3272b 2003 workerNode.info.ready &&
5eb72b9e 2004 !workerNode.info.stealing &&
b5e75be8 2005 workerNode.info.id !== workerId &&
0bc68267 2006 workerNode.usage.tasks.queued <
67f3f2d6
JB
2007 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2008 this.opts.tasksQueueOptions!.size! - sizeOffset
72695f86 2009 ) {
c63a35a0 2010 const workerInfo = this.getWorkerInfo(workerNodeKey)
1851fed0
JB
2011 if (workerInfo == null) {
2012 throw new Error(
2013 `Worker node with key '${workerNodeKey}' not found in pool`
2014 )
2015 }
c63a35a0 2016 workerInfo.stealing = true
67f3f2d6 2017 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2eee7220 2018 const task = sourceWorkerNode.dequeueLastPrioritizedTask()!
42c677c1 2019 this.handleTask(workerNodeKey, task)
67f3f2d6
JB
2020 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2021 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!)
c63a35a0 2022 workerInfo.stealing = false
10ecf8fd 2023 }
a2ed5053
JB
2024 }
2025 }
2026
be0676b3 2027 /**
fcd39179 2028 * This method is the message listener registered on each worker.
be0676b3 2029 */
3a776b6d
JB
2030 protected readonly workerMessageListener = (
2031 message: MessageValue<Response>
2032 ): void => {
fcd39179 2033 this.checkMessageWorkerId(message)
31847469
JB
2034 const { workerId, ready, taskId, taskFunctionsProperties } = message
2035 if (ready != null && taskFunctionsProperties != null) {
fcd39179
JB
2036 // Worker ready response received from worker
2037 this.handleWorkerReadyResponse(message)
31847469
JB
2038 } else if (taskFunctionsProperties != null) {
2039 // Task function properties message received from worker
9a55fa8c
JB
2040 const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
2041 const workerInfo = this.getWorkerInfo(workerNodeKey)
1851fed0 2042 if (workerInfo != null) {
31847469 2043 workerInfo.taskFunctionsProperties = taskFunctionsProperties
9a55fa8c 2044 this.sendStatisticsMessageToWorker(workerNodeKey)
1851fed0 2045 }
31847469
JB
2046 } else if (taskId != null) {
2047 // Task execution response received from worker
2048 this.handleTaskExecutionResponse(message)
6b272951
JB
2049 }
2050 }
2051
8e8d9101
JB
2052 private checkAndEmitReadyEvent (): void {
2053 if (!this.readyEventEmitted && this.ready) {
2054 this.emitter?.emit(PoolEvents.ready, this.info)
2055 this.readyEventEmitted = true
2056 }
2057 }
2058
10e2aa7e 2059 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
31847469 2060 const { workerId, ready, taskFunctionsProperties } = message
e44639e9 2061 if (ready == null || !ready) {
c63a35a0 2062 throw new Error(`Worker ${workerId} failed to initialize`)
f05ed93c 2063 }
9a55fa8c
JB
2064 const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
2065 const workerNode = this.workerNodes[workerNodeKey]
e44639e9 2066 workerNode.info.ready = ready
31847469 2067 workerNode.info.taskFunctionsProperties = taskFunctionsProperties
9a55fa8c 2068 this.sendStatisticsMessageToWorker(workerNodeKey)
8e8d9101 2069 this.checkAndEmitReadyEvent()
6b272951
JB
2070 }
2071
2072 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
463226a4 2073 const { workerId, taskId, workerError, data } = message
67f3f2d6
JB
2074 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2075 const promiseResponse = this.promiseResponseMap.get(taskId!)
6b272951 2076 if (promiseResponse != null) {
f18fd12b 2077 const { resolve, reject, workerNodeKey, asyncResource } = promiseResponse
9b358e72 2078 const workerNode = this.workerNodes[workerNodeKey]
6703b9f4
JB
2079 if (workerError != null) {
2080 this.emitter?.emit(PoolEvents.taskError, workerError)
f18fd12b
JB
2081 asyncResource != null
2082 ? asyncResource.runInAsyncScope(
2083 reject,
2084 this.emitter,
2085 workerError.message
2086 )
2087 : reject(workerError.message)
6b272951 2088 } else {
f18fd12b
JB
2089 asyncResource != null
2090 ? asyncResource.runInAsyncScope(resolve, this.emitter, data)
2091 : resolve(data as Response)
6b272951 2092 }
f18fd12b 2093 asyncResource?.emitDestroy()
501aea93 2094 this.afterTaskExecutionHook(workerNodeKey, message)
67f3f2d6
JB
2095 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2096 this.promiseResponseMap.delete(taskId!)
cdaecaee
JB
2097 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2098 workerNode?.emit('taskFinished', taskId)
16d7e943
JB
2099 if (
2100 this.opts.enableTasksQueue === true &&
2101 !this.destroying &&
2102 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2103 workerNode != null
2104 ) {
9b358e72 2105 const workerNodeTasksUsage = workerNode.usage.tasks
463226a4
JB
2106 if (
2107 this.tasksQueueSize(workerNodeKey) > 0 &&
2108 workerNodeTasksUsage.executing <
67f3f2d6
JB
2109 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2110 this.opts.tasksQueueOptions!.concurrency!
463226a4 2111 ) {
67f3f2d6
JB
2112 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2113 this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!)
463226a4
JB
2114 }
2115 if (
2116 workerNodeTasksUsage.executing === 0 &&
2117 this.tasksQueueSize(workerNodeKey) === 0 &&
2118 workerNodeTasksUsage.sequentiallyStolen === 0
2119 ) {
e44639e9 2120 workerNode.emit('idle', {
7f0e1334 2121 workerId,
e1c2dba7
JB
2122 workerNodeKey
2123 })
463226a4 2124 }
be0676b3
APA
2125 }
2126 }
be0676b3 2127 }
7c0ba920 2128
a1763c54 2129 private checkAndEmitTaskExecutionEvents (): void {
33e6bb4c
JB
2130 if (this.busy) {
2131 this.emitter?.emit(PoolEvents.busy, this.info)
a1763c54
JB
2132 }
2133 }
2134
2135 private checkAndEmitTaskQueuingEvents (): void {
2136 if (this.hasBackPressure()) {
2137 this.emitter?.emit(PoolEvents.backPressure, this.info)
164d950a
JB
2138 }
2139 }
2140
d0878034
JB
2141 /**
2142 * Emits dynamic worker creation events.
2143 */
2144 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
33e6bb4c 2145
8a1260a3 2146 /**
aa9eede8 2147 * Gets the worker information given its worker node key.
8a1260a3
JB
2148 *
2149 * @param workerNodeKey - The worker node key.
3f09ed9f 2150 * @returns The worker information.
8a1260a3 2151 */
1851fed0
JB
2152 protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined {
2153 return this.workerNodes[workerNodeKey]?.info
e221309a
JB
2154 }
2155
a05c10de 2156 /**
c3719753 2157 * Creates a worker node.
ea7a90d3 2158 *
c3719753 2159 * @returns The created worker node.
ea7a90d3 2160 */
c3719753 2161 private createWorkerNode (): IWorkerNode<Worker, Data> {
671d5154 2162 const workerNode = new WorkerNode<Worker, Data>(
c3719753
JB
2163 this.worker,
2164 this.filePath,
2165 {
2166 env: this.opts.env,
2167 workerOptions: this.opts.workerOptions,
2168 tasksQueueBackPressureSize:
32b141fd 2169 this.opts.tasksQueueOptions?.size ??
26ce26ca
JB
2170 getDefaultTasksQueueOptions(
2171 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
95d1a734
JB
2172 ).size,
2173 tasksQueueBucketSize:
2174 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) * 2
c3719753 2175 }
671d5154 2176 )
b97d82d8 2177 // Flag the worker node as ready at pool startup.
d2c73f82
JB
2178 if (this.starting) {
2179 workerNode.info.ready = true
2180 }
c3719753
JB
2181 return workerNode
2182 }
2183
2184 /**
2185 * Adds the given worker node in the pool worker nodes.
2186 *
2187 * @param workerNode - The worker node.
2188 * @returns The added worker node key.
2189 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
2190 */
2191 private addWorkerNode (workerNode: IWorkerNode<Worker, Data>): number {
aa9eede8 2192 this.workerNodes.push(workerNode)
c3719753 2193 const workerNodeKey = this.workerNodes.indexOf(workerNode)
aa9eede8 2194 if (workerNodeKey === -1) {
86ed0598 2195 throw new Error('Worker added not found in worker nodes')
aa9eede8
JB
2196 }
2197 return workerNodeKey
ea7a90d3 2198 }
c923ce56 2199
8e8d9101
JB
2200 private checkAndEmitEmptyEvent (): void {
2201 if (this.empty) {
2202 this.emitter?.emit(PoolEvents.empty, this.info)
2203 this.readyEventEmitted = false
2204 }
2205 }
2206
51fe3d3c 2207 /**
9974369e 2208 * Removes the worker node from the pool worker nodes.
51fe3d3c 2209 *
9974369e 2210 * @param workerNode - The worker node.
51fe3d3c 2211 */
9974369e
JB
2212 private removeWorkerNode (workerNode: IWorkerNode<Worker, Data>): void {
2213 const workerNodeKey = this.workerNodes.indexOf(workerNode)
1f68cede
JB
2214 if (workerNodeKey !== -1) {
2215 this.workerNodes.splice(workerNodeKey, 1)
bcfb06ce 2216 this.workerChoiceStrategiesContext?.remove(workerNodeKey)
1f68cede 2217 }
8e8d9101 2218 this.checkAndEmitEmptyEvent()
51fe3d3c 2219 }
adc3c320 2220
ae3ab61d 2221 protected flagWorkerNodeAsNotReady (workerNodeKey: number): void {
1851fed0
JB
2222 const workerInfo = this.getWorkerInfo(workerNodeKey)
2223 if (workerInfo != null) {
2224 workerInfo.ready = false
2225 }
ae3ab61d
JB
2226 }
2227
9e844245
JB
2228 private hasBackPressure (): boolean {
2229 return (
2230 this.opts.enableTasksQueue === true &&
2231 this.workerNodes.findIndex(
041dc05b 2232 workerNode => !workerNode.hasBackPressure()
a1763c54 2233 ) === -1
9e844245 2234 )
e2b31e32
JB
2235 }
2236
b0a4db63 2237 /**
aa9eede8 2238 * Executes the given task on the worker given its worker node key.
b0a4db63 2239 *
aa9eede8 2240 * @param workerNodeKey - The worker node key.
b0a4db63
JB
2241 * @param task - The task to execute.
2242 */
2e81254d 2243 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1c6fe997 2244 this.beforeTaskExecutionHook(workerNodeKey, task)
bbfa38a2 2245 this.sendToWorker(workerNodeKey, task, task.transferList)
a1763c54 2246 this.checkAndEmitTaskExecutionEvents()
2e81254d
JB
2247 }
2248
f9f00b5f 2249 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
a1763c54
JB
2250 const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
2251 this.checkAndEmitTaskQueuingEvents()
2252 return tasksQueueSize
adc3c320
JB
2253 }
2254
0d4e88b3
JB
2255 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
2256 return this.workerNodes[workerNodeKey].dequeueTask()
adc3c320
JB
2257 }
2258
416fd65c 2259 private tasksQueueSize (workerNodeKey: number): number {
4b628b48 2260 return this.workerNodes[workerNodeKey].tasksQueueSize()
df593701
JB
2261 }
2262
87347ea8
JB
2263 protected flushTasksQueue (workerNodeKey: number): number {
2264 let flushedTasks = 0
920278a2 2265 while (this.tasksQueueSize(workerNodeKey) > 0) {
67f3f2d6
JB
2266 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2267 this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!)
87347ea8 2268 ++flushedTasks
ff733df7 2269 }
4b628b48 2270 this.workerNodes[workerNodeKey].clearTasksQueue()
87347ea8 2271 return flushedTasks
ff733df7
JB
2272 }
2273
ef41a6e6 2274 private flushTasksQueues (): void {
19b8be8b 2275 for (const workerNodeKey of this.workerNodes.keys()) {
ef41a6e6
JB
2276 this.flushTasksQueue(workerNodeKey)
2277 }
2278 }
c97c7edb 2279}