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