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