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