refactor: move worker setup into worker node constructor
[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(
42c677c1
JB
309 (accumulator, _workerNode, workerNodeKey) =>
310 this.isWorkerNodeBusy(workerNodeKey) ? 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
42c677c1
JB
710 private isWorkerNodeBusy (workerNodeKey: number): boolean {
711 if (this.opts.enableTasksQueue === true) {
712 return (
713 this.workerNodes[workerNodeKey].usage.tasks.executing >=
714 (this.opts.tasksQueueOptions?.concurrency as number)
715 )
716 }
717 return this.workerNodes[workerNodeKey].usage.tasks.executing > 0
718 }
719
e81c38f2 720 private async sendTaskFunctionOperationToWorker (
72ae84a2
JB
721 workerNodeKey: number,
722 message: MessageValue<Data>
723 ): Promise<boolean> {
72ae84a2 724 return await new Promise<boolean>((resolve, reject) => {
ae036c3e
JB
725 const taskFunctionOperationListener = (
726 message: MessageValue<Response>
727 ): void => {
728 this.checkMessageWorkerId(message)
729 const workerId = this.getWorkerInfo(workerNodeKey).id as number
72ae84a2 730 if (
ae036c3e
JB
731 message.taskFunctionOperationStatus != null &&
732 message.workerId === workerId
72ae84a2 733 ) {
ae036c3e
JB
734 if (message.taskFunctionOperationStatus) {
735 resolve(true)
736 } else if (!message.taskFunctionOperationStatus) {
737 reject(
738 new Error(
739 `Task function operation '${
740 message.taskFunctionOperation as string
741 }' failed on worker ${message.workerId} with error: '${
742 message.workerError?.message as string
743 }'`
744 )
72ae84a2 745 )
ae036c3e
JB
746 }
747 this.deregisterWorkerMessageListener(
748 this.getWorkerNodeKeyByWorkerId(message.workerId),
749 taskFunctionOperationListener
72ae84a2
JB
750 )
751 }
ae036c3e
JB
752 }
753 this.registerWorkerMessageListener(
754 workerNodeKey,
755 taskFunctionOperationListener
756 )
72ae84a2
JB
757 this.sendToWorker(workerNodeKey, message)
758 })
759 }
760
761 private async sendTaskFunctionOperationToWorkers (
adee6053 762 message: MessageValue<Data>
e81c38f2
JB
763 ): Promise<boolean> {
764 return await new Promise<boolean>((resolve, reject) => {
ae036c3e
JB
765 const responsesReceived = new Array<MessageValue<Response>>()
766 const taskFunctionOperationsListener = (
767 message: MessageValue<Response>
768 ): void => {
769 this.checkMessageWorkerId(message)
770 if (message.taskFunctionOperationStatus != null) {
771 responsesReceived.push(message)
772 if (responsesReceived.length === this.workerNodes.length) {
e81c38f2 773 if (
e81c38f2
JB
774 responsesReceived.every(
775 message => message.taskFunctionOperationStatus === true
776 )
777 ) {
778 resolve(true)
779 } else if (
e81c38f2
JB
780 responsesReceived.some(
781 message => message.taskFunctionOperationStatus === false
782 )
783 ) {
b0b55f57
JB
784 const errorResponse = responsesReceived.find(
785 response => response.taskFunctionOperationStatus === false
786 )
e81c38f2
JB
787 reject(
788 new Error(
b0b55f57 789 `Task function operation '${
e81c38f2 790 message.taskFunctionOperation as string
b0b55f57
JB
791 }' failed on worker ${
792 errorResponse?.workerId as number
793 } with error: '${
794 errorResponse?.workerError?.message as string
795 }'`
e81c38f2
JB
796 )
797 )
798 }
ae036c3e
JB
799 this.deregisterWorkerMessageListener(
800 this.getWorkerNodeKeyByWorkerId(message.workerId),
801 taskFunctionOperationsListener
802 )
e81c38f2 803 }
ae036c3e
JB
804 }
805 }
806 for (const [workerNodeKey] of this.workerNodes.entries()) {
807 this.registerWorkerMessageListener(
808 workerNodeKey,
809 taskFunctionOperationsListener
810 )
72ae84a2 811 this.sendToWorker(workerNodeKey, message)
e81c38f2
JB
812 }
813 })
6703b9f4
JB
814 }
815
816 /** @inheritDoc */
817 public hasTaskFunction (name: string): boolean {
edbc15c6
JB
818 for (const workerNode of this.workerNodes) {
819 if (
820 Array.isArray(workerNode.info.taskFunctionNames) &&
821 workerNode.info.taskFunctionNames.includes(name)
822 ) {
823 return true
824 }
825 }
826 return false
6703b9f4
JB
827 }
828
829 /** @inheritDoc */
e81c38f2
JB
830 public async addTaskFunction (
831 name: string,
3feeab69 832 fn: TaskFunction<Data, Response>
e81c38f2 833 ): Promise<boolean> {
3feeab69
JB
834 if (typeof name !== 'string') {
835 throw new TypeError('name argument must be a string')
836 }
837 if (typeof name === 'string' && name.trim().length === 0) {
838 throw new TypeError('name argument must not be an empty string')
839 }
840 if (typeof fn !== 'function') {
841 throw new TypeError('fn argument must be a function')
842 }
adee6053 843 const opResult = await this.sendTaskFunctionOperationToWorkers({
6703b9f4
JB
844 taskFunctionOperation: 'add',
845 taskFunctionName: name,
3feeab69 846 taskFunction: fn.toString()
6703b9f4 847 })
adee6053
JB
848 this.taskFunctions.set(name, fn)
849 return opResult
6703b9f4
JB
850 }
851
852 /** @inheritDoc */
e81c38f2 853 public async removeTaskFunction (name: string): Promise<boolean> {
9eae3c69
JB
854 if (!this.taskFunctions.has(name)) {
855 throw new Error(
16248b23 856 'Cannot remove a task function not handled on the pool side'
9eae3c69
JB
857 )
858 }
adee6053 859 const opResult = await this.sendTaskFunctionOperationToWorkers({
6703b9f4
JB
860 taskFunctionOperation: 'remove',
861 taskFunctionName: name
862 })
adee6053
JB
863 this.deleteTaskFunctionWorkerUsages(name)
864 this.taskFunctions.delete(name)
865 return opResult
6703b9f4
JB
866 }
867
90d7d101 868 /** @inheritDoc */
6703b9f4 869 public listTaskFunctionNames (): string[] {
f2dbbf95
JB
870 for (const workerNode of this.workerNodes) {
871 if (
6703b9f4
JB
872 Array.isArray(workerNode.info.taskFunctionNames) &&
873 workerNode.info.taskFunctionNames.length > 0
f2dbbf95 874 ) {
6703b9f4 875 return workerNode.info.taskFunctionNames
f2dbbf95 876 }
90d7d101 877 }
f2dbbf95 878 return []
90d7d101
JB
879 }
880
6703b9f4 881 /** @inheritDoc */
e81c38f2 882 public async setDefaultTaskFunction (name: string): Promise<boolean> {
72ae84a2 883 return await this.sendTaskFunctionOperationToWorkers({
6703b9f4
JB
884 taskFunctionOperation: 'default',
885 taskFunctionName: name
886 })
6703b9f4
JB
887 }
888
adee6053
JB
889 private deleteTaskFunctionWorkerUsages (name: string): void {
890 for (const workerNode of this.workerNodes) {
891 workerNode.deleteTaskFunctionWorkerUsage(name)
892 }
893 }
894
375f7504
JB
895 private shallExecuteTask (workerNodeKey: number): boolean {
896 return (
897 this.tasksQueueSize(workerNodeKey) === 0 &&
898 this.workerNodes[workerNodeKey].usage.tasks.executing <
899 (this.opts.tasksQueueOptions?.concurrency as number)
900 )
901 }
902
afc003b2 903 /** @inheritDoc */
7d91a8cd
JB
904 public async execute (
905 data?: Data,
906 name?: string,
907 transferList?: TransferListItem[]
908 ): Promise<Response> {
52b71763 909 return await new Promise<Response>((resolve, reject) => {
15b176e0 910 if (!this.started) {
47352846 911 reject(new Error('Cannot execute a task on not started pool'))
9d2d0da1 912 return
15b176e0 913 }
711623b8
JB
914 if (this.destroying) {
915 reject(new Error('Cannot execute a task on destroying pool'))
916 return
917 }
7d91a8cd
JB
918 if (name != null && typeof name !== 'string') {
919 reject(new TypeError('name argument must be a string'))
9d2d0da1 920 return
7d91a8cd 921 }
90d7d101
JB
922 if (
923 name != null &&
924 typeof name === 'string' &&
925 name.trim().length === 0
926 ) {
f58b60b9 927 reject(new TypeError('name argument must not be an empty string'))
9d2d0da1 928 return
90d7d101 929 }
b558f6b5
JB
930 if (transferList != null && !Array.isArray(transferList)) {
931 reject(new TypeError('transferList argument must be an array'))
9d2d0da1 932 return
b558f6b5
JB
933 }
934 const timestamp = performance.now()
935 const workerNodeKey = this.chooseWorkerNode()
501aea93 936 const task: Task<Data> = {
52b71763
JB
937 name: name ?? DEFAULT_TASK_NAME,
938 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
939 data: data ?? ({} as Data),
7d91a8cd 940 transferList,
52b71763 941 timestamp,
7629bdf1 942 taskId: randomUUID()
52b71763 943 }
7629bdf1 944 this.promiseResponseMap.set(task.taskId as string, {
2e81254d
JB
945 resolve,
946 reject,
f18fd12b
JB
947 workerNodeKey,
948 ...(this.emitter != null && {
949 asyncResource: new AsyncResource('poolifier:task', {
950 triggerAsyncId: this.emitter.asyncId,
951 requireManualDestroy: true
952 })
953 })
2e81254d 954 })
52b71763 955 if (
4e377863
JB
956 this.opts.enableTasksQueue === false ||
957 (this.opts.enableTasksQueue === true &&
375f7504 958 this.shallExecuteTask(workerNodeKey))
52b71763 959 ) {
501aea93 960 this.executeTask(workerNodeKey, task)
4e377863
JB
961 } else {
962 this.enqueueTask(workerNodeKey, task)
52b71763 963 }
2e81254d 964 })
280c2a77 965 }
c97c7edb 966
47352846
JB
967 /** @inheritdoc */
968 public start (): void {
711623b8
JB
969 if (this.started) {
970 throw new Error('Cannot start an already started pool')
971 }
972 if (this.starting) {
973 throw new Error('Cannot start an already starting pool')
974 }
975 if (this.destroying) {
976 throw new Error('Cannot start a destroying pool')
977 }
47352846
JB
978 this.starting = true
979 while (
980 this.workerNodes.reduce(
981 (accumulator, workerNode) =>
982 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
983 0
984 ) < this.numberOfWorkers
985 ) {
986 this.createAndSetupWorkerNode()
987 }
988 this.starting = false
989 this.started = true
990 }
991
afc003b2 992 /** @inheritDoc */
c97c7edb 993 public async destroy (): Promise<void> {
711623b8
JB
994 if (!this.started) {
995 throw new Error('Cannot destroy an already destroyed pool')
996 }
997 if (this.starting) {
998 throw new Error('Cannot destroy an starting pool')
999 }
1000 if (this.destroying) {
1001 throw new Error('Cannot destroy an already destroying pool')
1002 }
1003 this.destroying = true
1fbcaa7c 1004 await Promise.all(
14c39df1 1005 this.workerNodes.map(async (_workerNode, workerNodeKey) => {
aa9eede8 1006 await this.destroyWorkerNode(workerNodeKey)
1fbcaa7c
JB
1007 })
1008 )
33e6bb4c 1009 this.emitter?.emit(PoolEvents.destroy, this.info)
f80125ca 1010 this.emitter?.emitDestroy()
78f60f82 1011 this.emitter?.removeAllListeners()
55082af9 1012 this.readyEventEmitted = false
711623b8 1013 this.destroying = false
15b176e0 1014 this.started = false
c97c7edb
S
1015 }
1016
1e3214b6 1017 protected async sendKillMessageToWorker (
72ae84a2 1018 workerNodeKey: number
1e3214b6 1019 ): Promise<void> {
9edb9717 1020 await new Promise<void>((resolve, reject) => {
ae036c3e
JB
1021 const killMessageListener = (message: MessageValue<Response>): void => {
1022 this.checkMessageWorkerId(message)
1e3214b6
JB
1023 if (message.kill === 'success') {
1024 resolve()
1025 } else if (message.kill === 'failure') {
72ae84a2
JB
1026 reject(
1027 new Error(
ae036c3e 1028 `Kill message handling failed on worker ${
72ae84a2 1029 message.workerId as number
ae036c3e 1030 }`
72ae84a2
JB
1031 )
1032 )
1e3214b6 1033 }
ae036c3e 1034 }
51d9cfbd 1035 // FIXME: should be registered only once
ae036c3e 1036 this.registerWorkerMessageListener(workerNodeKey, killMessageListener)
72ae84a2 1037 this.sendToWorker(workerNodeKey, { kill: true })
1e3214b6 1038 })
1e3214b6
JB
1039 }
1040
4a6952ff 1041 /**
aa9eede8 1042 * Terminates the worker node given its worker node key.
4a6952ff 1043 *
aa9eede8 1044 * @param workerNodeKey - The worker node key.
4a6952ff 1045 */
81c02522 1046 protected abstract destroyWorkerNode (workerNodeKey: number): Promise<void>
c97c7edb 1047
729c563d 1048 /**
6677a3d3
JB
1049 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1050 * Can be overridden.
afc003b2
JB
1051 *
1052 * @virtual
729c563d 1053 */
280c2a77 1054 protected setupHook (): void {
965df41c 1055 /* Intentionally empty */
280c2a77 1056 }
c97c7edb 1057
729c563d 1058 /**
280c2a77
S
1059 * Should return whether the worker is the main worker or not.
1060 */
1061 protected abstract isMain (): boolean
1062
1063 /**
2e81254d 1064 * Hook executed before the worker task execution.
bf9549ae 1065 * Can be overridden.
729c563d 1066 *
f06e48d8 1067 * @param workerNodeKey - The worker node key.
1c6fe997 1068 * @param task - The task to execute.
729c563d 1069 */
1c6fe997
JB
1070 protected beforeTaskExecutionHook (
1071 workerNodeKey: number,
1072 task: Task<Data>
1073 ): void {
94407def
JB
1074 if (this.workerNodes[workerNodeKey]?.usage != null) {
1075 const workerUsage = this.workerNodes[workerNodeKey].usage
1076 ++workerUsage.tasks.executing
1077 this.updateWaitTimeWorkerUsage(workerUsage, task)
1078 }
1079 if (
1080 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1081 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
1082 task.name as string
1083 ) != null
1084 ) {
db0e38ee 1085 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 1086 workerNodeKey
db0e38ee 1087 ].getTaskFunctionWorkerUsage(task.name as string) as WorkerUsage
5623b8d5
JB
1088 ++taskFunctionWorkerUsage.tasks.executing
1089 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage, task)
b558f6b5 1090 }
c97c7edb
S
1091 }
1092
c01733f1 1093 /**
2e81254d 1094 * Hook executed after the worker task execution.
bf9549ae 1095 * Can be overridden.
c01733f1 1096 *
501aea93 1097 * @param workerNodeKey - The worker node key.
38e795c1 1098 * @param message - The received message.
c01733f1 1099 */
2e81254d 1100 protected afterTaskExecutionHook (
501aea93 1101 workerNodeKey: number,
2740a743 1102 message: MessageValue<Response>
bf9549ae 1103 ): void {
94407def
JB
1104 if (this.workerNodes[workerNodeKey]?.usage != null) {
1105 const workerUsage = this.workerNodes[workerNodeKey].usage
1106 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
1107 this.updateRunTimeWorkerUsage(workerUsage, message)
1108 this.updateEluWorkerUsage(workerUsage, message)
1109 }
1110 if (
1111 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1112 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
5623b8d5 1113 message.taskPerformance?.name as string
94407def
JB
1114 ) != null
1115 ) {
db0e38ee 1116 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 1117 workerNodeKey
db0e38ee 1118 ].getTaskFunctionWorkerUsage(
0628755c 1119 message.taskPerformance?.name as string
b558f6b5 1120 ) as WorkerUsage
db0e38ee
JB
1121 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
1122 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage, message)
1123 this.updateEluWorkerUsage(taskFunctionWorkerUsage, message)
b558f6b5
JB
1124 }
1125 }
1126
db0e38ee
JB
1127 /**
1128 * Whether the worker node shall update its task function worker usage or not.
1129 *
1130 * @param workerNodeKey - The worker node key.
1131 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1132 */
1133 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
a5d15204 1134 const workerInfo = this.getWorkerInfo(workerNodeKey)
b558f6b5 1135 return (
94407def 1136 workerInfo != null &&
6703b9f4
JB
1137 Array.isArray(workerInfo.taskFunctionNames) &&
1138 workerInfo.taskFunctionNames.length > 2
b558f6b5 1139 )
f1c06930
JB
1140 }
1141
1142 private updateTaskStatisticsWorkerUsage (
1143 workerUsage: WorkerUsage,
1144 message: MessageValue<Response>
1145 ): void {
a4e07f72 1146 const workerTaskStatistics = workerUsage.tasks
5bb5be17
JB
1147 if (
1148 workerTaskStatistics.executing != null &&
1149 workerTaskStatistics.executing > 0
1150 ) {
1151 --workerTaskStatistics.executing
5bb5be17 1152 }
6703b9f4 1153 if (message.workerError == null) {
98e72cda
JB
1154 ++workerTaskStatistics.executed
1155 } else {
a4e07f72 1156 ++workerTaskStatistics.failed
2740a743 1157 }
f8eb0a2a
JB
1158 }
1159
a4e07f72
JB
1160 private updateRunTimeWorkerUsage (
1161 workerUsage: WorkerUsage,
f8eb0a2a
JB
1162 message: MessageValue<Response>
1163 ): void {
6703b9f4 1164 if (message.workerError != null) {
dc021bcc
JB
1165 return
1166 }
e4f20deb
JB
1167 updateMeasurementStatistics(
1168 workerUsage.runTime,
1169 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime,
dc021bcc 1170 message.taskPerformance?.runTime ?? 0
e4f20deb 1171 )
f8eb0a2a
JB
1172 }
1173
a4e07f72
JB
1174 private updateWaitTimeWorkerUsage (
1175 workerUsage: WorkerUsage,
1c6fe997 1176 task: Task<Data>
f8eb0a2a 1177 ): void {
1c6fe997
JB
1178 const timestamp = performance.now()
1179 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
e4f20deb
JB
1180 updateMeasurementStatistics(
1181 workerUsage.waitTime,
1182 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime,
dc021bcc 1183 taskWaitTime
e4f20deb 1184 )
c01733f1 1185 }
1186
a4e07f72 1187 private updateEluWorkerUsage (
5df69fab 1188 workerUsage: WorkerUsage,
62c15a68
JB
1189 message: MessageValue<Response>
1190 ): void {
6703b9f4 1191 if (message.workerError != null) {
dc021bcc
JB
1192 return
1193 }
008512c7
JB
1194 const eluTaskStatisticsRequirements: MeasurementStatisticsRequirements =
1195 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
e4f20deb
JB
1196 updateMeasurementStatistics(
1197 workerUsage.elu.active,
008512c7 1198 eluTaskStatisticsRequirements,
dc021bcc 1199 message.taskPerformance?.elu?.active ?? 0
e4f20deb
JB
1200 )
1201 updateMeasurementStatistics(
1202 workerUsage.elu.idle,
008512c7 1203 eluTaskStatisticsRequirements,
dc021bcc 1204 message.taskPerformance?.elu?.idle ?? 0
e4f20deb 1205 )
008512c7 1206 if (eluTaskStatisticsRequirements.aggregate) {
f7510105 1207 if (message.taskPerformance?.elu != null) {
f7510105
JB
1208 if (workerUsage.elu.utilization != null) {
1209 workerUsage.elu.utilization =
1210 (workerUsage.elu.utilization +
1211 message.taskPerformance.elu.utilization) /
1212 2
1213 } else {
1214 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
1215 }
62c15a68
JB
1216 }
1217 }
1218 }
1219
280c2a77 1220 /**
f06e48d8 1221 * Chooses a worker node for the next task.
280c2a77 1222 *
6c6afb84 1223 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
280c2a77 1224 *
aa9eede8 1225 * @returns The chosen worker node key
280c2a77 1226 */
6c6afb84 1227 private chooseWorkerNode (): number {
930dcf12 1228 if (this.shallCreateDynamicWorker()) {
aa9eede8 1229 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
6c6afb84 1230 if (
b1aae695 1231 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
6c6afb84 1232 ) {
aa9eede8 1233 return workerNodeKey
6c6afb84 1234 }
17393ac8 1235 }
930dcf12
JB
1236 return this.workerChoiceStrategyContext.execute()
1237 }
1238
6c6afb84
JB
1239 /**
1240 * Conditions for dynamic worker creation.
1241 *
1242 * @returns Whether to create a dynamic worker or not.
1243 */
1244 private shallCreateDynamicWorker (): boolean {
930dcf12 1245 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
c97c7edb
S
1246 }
1247
280c2a77 1248 /**
aa9eede8 1249 * Sends a message to worker given its worker node key.
280c2a77 1250 *
aa9eede8 1251 * @param workerNodeKey - The worker node key.
38e795c1 1252 * @param message - The message.
7d91a8cd 1253 * @param transferList - The optional array of transferable objects.
280c2a77
S
1254 */
1255 protected abstract sendToWorker (
aa9eede8 1256 workerNodeKey: number,
7d91a8cd
JB
1257 message: MessageValue<Data>,
1258 transferList?: TransferListItem[]
280c2a77
S
1259 ): void
1260
4a6952ff 1261 /**
aa9eede8 1262 * Creates a new, completely set up worker node.
4a6952ff 1263 *
aa9eede8 1264 * @returns New, completely set up worker node key.
4a6952ff 1265 */
aa9eede8 1266 protected createAndSetupWorkerNode (): number {
c3719753
JB
1267 const workerNode = this.createWorkerNode()
1268 workerNode.registerWorkerEventHandler(
1269 'online',
1270 this.opts.onlineHandler ?? EMPTY_FUNCTION
1271 )
1272 workerNode.registerWorkerEventHandler(
1273 'message',
1274 this.opts.messageHandler ?? EMPTY_FUNCTION
1275 )
1276 workerNode.registerWorkerEventHandler(
1277 'error',
1278 this.opts.errorHandler ?? EMPTY_FUNCTION
1279 )
1280 workerNode.registerWorkerEventHandler('error', (error: Error) => {
1281 const workerNodeKey = this.getWorkerNodeKeyByWorker(workerNode.worker)
23b11f60 1282 this.flagWorkerNodeAsNotReady(workerNodeKey)
46b0bb09 1283 const workerInfo = this.getWorkerInfo(workerNodeKey)
2a69b8c5 1284 this.emitter?.emit(PoolEvents.error, error)
cce7d657 1285 this.workerNodes[workerNodeKey].closeChannel()
15b176e0 1286 if (
b6bfca01 1287 this.started &&
9b38ab2d 1288 !this.starting &&
711623b8 1289 !this.destroying &&
9b38ab2d 1290 this.opts.restartWorkerOnError === true
15b176e0 1291 ) {
9b106837 1292 if (workerInfo.dynamic) {
aa9eede8 1293 this.createAndSetupDynamicWorkerNode()
8a1260a3 1294 } else {
aa9eede8 1295 this.createAndSetupWorkerNode()
8a1260a3 1296 }
5baee0d7 1297 }
6d59c3a3 1298 if (this.started && this.opts.enableTasksQueue === true) {
9b106837 1299 this.redistributeQueuedTasks(workerNodeKey)
19dbc45b 1300 }
5baee0d7 1301 })
c3719753
JB
1302 workerNode.registerWorkerEventHandler(
1303 'exit',
1304 this.opts.exitHandler ?? EMPTY_FUNCTION
1305 )
1306 workerNode.registerOnceWorkerEventHandler('exit', () => {
1307 this.removeWorkerNode(workerNode.worker)
a974afa6 1308 })
c3719753 1309 const workerNodeKey = this.addWorkerNode(workerNode)
aa9eede8 1310 this.afterWorkerNodeSetup(workerNodeKey)
aa9eede8 1311 return workerNodeKey
c97c7edb 1312 }
be0676b3 1313
930dcf12 1314 /**
aa9eede8 1315 * Creates a new, completely set up dynamic worker node.
930dcf12 1316 *
aa9eede8 1317 * @returns New, completely set up dynamic worker node key.
930dcf12 1318 */
aa9eede8
JB
1319 protected createAndSetupDynamicWorkerNode (): number {
1320 const workerNodeKey = this.createAndSetupWorkerNode()
041dc05b 1321 this.registerWorkerMessageListener(workerNodeKey, message => {
4d159167 1322 this.checkMessageWorkerId(message)
aa9eede8
JB
1323 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
1324 message.workerId
aad6fb64 1325 )
aa9eede8 1326 const workerUsage = this.workerNodes[localWorkerNodeKey].usage
81c02522 1327 // Kill message received from worker
930dcf12
JB
1328 if (
1329 isKillBehavior(KillBehaviors.HARD, message.kill) ||
1e3214b6 1330 (isKillBehavior(KillBehaviors.SOFT, message.kill) &&
7b56f532 1331 ((this.opts.enableTasksQueue === false &&
aa9eede8 1332 workerUsage.tasks.executing === 0) ||
7b56f532 1333 (this.opts.enableTasksQueue === true &&
aa9eede8
JB
1334 workerUsage.tasks.executing === 0 &&
1335 this.tasksQueueSize(localWorkerNodeKey) === 0)))
930dcf12 1336 ) {
f3827d5d 1337 // Flag the worker node as not ready immediately
ae3ab61d 1338 this.flagWorkerNodeAsNotReady(localWorkerNodeKey)
041dc05b 1339 this.destroyWorkerNode(localWorkerNodeKey).catch(error => {
5270d253
JB
1340 this.emitter?.emit(PoolEvents.error, error)
1341 })
930dcf12
JB
1342 }
1343 })
46b0bb09 1344 const workerInfo = this.getWorkerInfo(workerNodeKey)
aa9eede8 1345 this.sendToWorker(workerNodeKey, {
e9dd5b66 1346 checkActive: true
21f710aa 1347 })
72ae84a2
JB
1348 if (this.taskFunctions.size > 0) {
1349 for (const [taskFunctionName, taskFunction] of this.taskFunctions) {
1350 this.sendTaskFunctionOperationToWorker(workerNodeKey, {
1351 taskFunctionOperation: 'add',
1352 taskFunctionName,
1353 taskFunction: taskFunction.toString()
1354 }).catch(error => {
1355 this.emitter?.emit(PoolEvents.error, error)
1356 })
1357 }
1358 }
b5e113f6 1359 workerInfo.dynamic = true
b1aae695
JB
1360 if (
1361 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerReady ||
1362 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
1363 ) {
b5e113f6
JB
1364 workerInfo.ready = true
1365 }
33e6bb4c 1366 this.checkAndEmitDynamicWorkerCreationEvents()
aa9eede8 1367 return workerNodeKey
930dcf12
JB
1368 }
1369
a2ed5053 1370 /**
aa9eede8 1371 * Registers a listener callback on the worker given its worker node key.
a2ed5053 1372 *
aa9eede8 1373 * @param workerNodeKey - The worker node key.
a2ed5053
JB
1374 * @param listener - The message listener callback.
1375 */
85aeb3f3
JB
1376 protected abstract registerWorkerMessageListener<
1377 Message extends Data | Response
aa9eede8
JB
1378 >(
1379 workerNodeKey: number,
1380 listener: (message: MessageValue<Message>) => void
1381 ): void
a2ed5053 1382
ae036c3e
JB
1383 /**
1384 * Registers once a listener callback on the worker given its worker node key.
1385 *
1386 * @param workerNodeKey - The worker node key.
1387 * @param listener - The message listener callback.
1388 */
1389 protected abstract registerOnceWorkerMessageListener<
1390 Message extends Data | Response
1391 >(
1392 workerNodeKey: number,
1393 listener: (message: MessageValue<Message>) => void
1394 ): void
1395
1396 /**
1397 * Deregisters a listener callback on the worker given its worker node key.
1398 *
1399 * @param workerNodeKey - The worker node key.
1400 * @param listener - The message listener callback.
1401 */
1402 protected abstract deregisterWorkerMessageListener<
1403 Message extends Data | Response
1404 >(
1405 workerNodeKey: number,
1406 listener: (message: MessageValue<Message>) => void
1407 ): void
1408
a2ed5053 1409 /**
aa9eede8 1410 * Method hooked up after a worker node has been newly created.
a2ed5053
JB
1411 * Can be overridden.
1412 *
aa9eede8 1413 * @param workerNodeKey - The newly created worker node key.
a2ed5053 1414 */
aa9eede8 1415 protected afterWorkerNodeSetup (workerNodeKey: number): void {
a2ed5053 1416 // Listen to worker messages.
fcd39179
JB
1417 this.registerWorkerMessageListener(
1418 workerNodeKey,
3a776b6d 1419 this.workerMessageListener
fcd39179 1420 )
85aeb3f3 1421 // Send the startup message to worker.
aa9eede8 1422 this.sendStartupMessageToWorker(workerNodeKey)
9edb9717
JB
1423 // Send the statistics message to worker.
1424 this.sendStatisticsMessageToWorker(workerNodeKey)
72695f86 1425 if (this.opts.enableTasksQueue === true) {
dbd73092 1426 if (this.opts.tasksQueueOptions?.taskStealing === true) {
e1c2dba7 1427 this.workerNodes[workerNodeKey].on(
65542a35 1428 'idleWorkerNode',
e1c2dba7 1429 this.handleIdleWorkerNodeEvent
9f95d5eb 1430 )
47352846
JB
1431 }
1432 if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) {
e1c2dba7 1433 this.workerNodes[workerNodeKey].on(
b5e75be8 1434 'backPressure',
e1c2dba7 1435 this.handleBackPressureEvent
9f95d5eb 1436 )
47352846 1437 }
72695f86 1438 }
d2c73f82
JB
1439 }
1440
85aeb3f3 1441 /**
aa9eede8
JB
1442 * Sends the startup message to worker given its worker node key.
1443 *
1444 * @param workerNodeKey - The worker node key.
1445 */
1446 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
1447
1448 /**
9edb9717 1449 * Sends the statistics message to worker given its worker node key.
85aeb3f3 1450 *
aa9eede8 1451 * @param workerNodeKey - The worker node key.
85aeb3f3 1452 */
9edb9717 1453 private sendStatisticsMessageToWorker (workerNodeKey: number): void {
aa9eede8
JB
1454 this.sendToWorker(workerNodeKey, {
1455 statistics: {
1456 runTime:
1457 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1458 .runTime.aggregate,
1459 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1460 .elu.aggregate
72ae84a2 1461 }
aa9eede8
JB
1462 })
1463 }
a2ed5053 1464
42c677c1
JB
1465 private handleTask (workerNodeKey: number, task: Task<Data>): void {
1466 if (this.shallExecuteTask(workerNodeKey)) {
1467 this.executeTask(workerNodeKey, task)
1468 } else {
1469 this.enqueueTask(workerNodeKey, task)
1470 }
1471 }
1472
a2ed5053 1473 private redistributeQueuedTasks (workerNodeKey: number): void {
cb71d660
JB
1474 if (this.workerNodes.length <= 1) {
1475 return
1476 }
a2ed5053 1477 while (this.tasksQueueSize(workerNodeKey) > 0) {
f201a0cd
JB
1478 const destinationWorkerNodeKey = this.workerNodes.reduce(
1479 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
852ed3e4
JB
1480 return workerNode.info.ready &&
1481 workerNode.usage.tasks.queued <
1482 workerNodes[minWorkerNodeKey].usage.tasks.queued
f201a0cd
JB
1483 ? workerNodeKey
1484 : minWorkerNodeKey
1485 },
1486 0
1487 )
42c677c1
JB
1488 this.handleTask(
1489 destinationWorkerNodeKey,
1490 this.dequeueTask(workerNodeKey) as Task<Data>
1491 )
dd951876
JB
1492 }
1493 }
1494
b1838604
JB
1495 private updateTaskStolenStatisticsWorkerUsage (
1496 workerNodeKey: number,
b1838604
JB
1497 taskName: string
1498 ): void {
1a880eca 1499 const workerNode = this.workerNodes[workerNodeKey]
b1838604
JB
1500 if (workerNode?.usage != null) {
1501 ++workerNode.usage.tasks.stolen
1502 }
1503 if (
1504 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1505 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1506 ) {
1507 const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
1508 taskName
1509 ) as WorkerUsage
1510 ++taskFunctionWorkerUsage.tasks.stolen
1511 }
1512 }
1513
463226a4 1514 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
f1f77f45 1515 workerNodeKey: number
463226a4
JB
1516 ): void {
1517 const workerNode = this.workerNodes[workerNodeKey]
1518 if (workerNode?.usage != null) {
1519 ++workerNode.usage.tasks.sequentiallyStolen
1520 }
f1f77f45
JB
1521 }
1522
1523 private updateTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage (
1524 workerNodeKey: number,
1525 taskName: string
1526 ): void {
1527 const workerNode = this.workerNodes[workerNodeKey]
463226a4
JB
1528 if (
1529 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1530 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1531 ) {
1532 const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
1533 taskName
1534 ) as WorkerUsage
1535 ++taskFunctionWorkerUsage.tasks.sequentiallyStolen
1536 }
1537 }
1538
1539 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
f1f77f45 1540 workerNodeKey: number
463226a4
JB
1541 ): void {
1542 const workerNode = this.workerNodes[workerNodeKey]
1543 if (workerNode?.usage != null) {
1544 workerNode.usage.tasks.sequentiallyStolen = 0
1545 }
f1f77f45
JB
1546 }
1547
1548 private resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage (
1549 workerNodeKey: number,
1550 taskName: string
1551 ): void {
1552 const workerNode = this.workerNodes[workerNodeKey]
463226a4
JB
1553 if (
1554 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1555 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1556 ) {
1557 const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
1558 taskName
1559 ) as WorkerUsage
1560 taskFunctionWorkerUsage.tasks.sequentiallyStolen = 0
1561 }
1562 }
1563
65542a35 1564 private readonly handleIdleWorkerNodeEvent = (
e1c2dba7 1565 eventDetail: WorkerNodeEventDetail,
463226a4 1566 previousStolenTask?: Task<Data>
9f95d5eb 1567 ): void => {
cb71d660
JB
1568 if (this.workerNodes.length <= 1) {
1569 return
1570 }
e1c2dba7 1571 const { workerNodeKey } = eventDetail
463226a4
JB
1572 if (workerNodeKey == null) {
1573 throw new Error(
1574 'WorkerNode event detail workerNodeKey attribute must be defined'
1575 )
1576 }
1577 const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks
1578 if (
1579 previousStolenTask != null &&
1580 workerNodeTasksUsage.sequentiallyStolen > 0 &&
1581 (workerNodeTasksUsage.executing > 0 ||
1582 this.tasksQueueSize(workerNodeKey) > 0)
1583 ) {
f1f77f45
JB
1584 for (const taskName of this.workerNodes[workerNodeKey].info
1585 .taskFunctionNames as string[]) {
1586 this.resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1587 workerNodeKey,
1588 taskName
1589 )
1590 }
1591 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(workerNodeKey)
463226a4
JB
1592 return
1593 }
1594 const stolenTask = this.workerNodeStealTask(workerNodeKey)
f1f77f45
JB
1595 if (
1596 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1597 stolenTask != null
1598 ) {
1599 const taskFunctionTasksWorkerUsage = this.workerNodes[
1600 workerNodeKey
1601 ].getTaskFunctionWorkerUsage(stolenTask.name as string)
1602 ?.tasks as TaskStatistics
1603 if (
1604 taskFunctionTasksWorkerUsage.sequentiallyStolen === 0 ||
1605 (previousStolenTask != null &&
1606 previousStolenTask.name === stolenTask.name &&
1607 taskFunctionTasksWorkerUsage.sequentiallyStolen > 0)
1608 ) {
1609 this.updateTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1610 workerNodeKey,
1611 stolenTask.name as string
1612 )
1613 } else {
1614 this.resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1615 workerNodeKey,
1616 stolenTask.name as string
1617 )
1618 }
1619 }
463226a4
JB
1620 sleep(exponentialDelay(workerNodeTasksUsage.sequentiallyStolen))
1621 .then(() => {
e1c2dba7 1622 this.handleIdleWorkerNodeEvent(eventDetail, stolenTask)
463226a4
JB
1623 return undefined
1624 })
1625 .catch(EMPTY_FUNCTION)
1626 }
1627
1628 private readonly workerNodeStealTask = (
1629 workerNodeKey: number
1630 ): Task<Data> | undefined => {
dd951876 1631 const workerNodes = this.workerNodes
a6b3272b 1632 .slice()
dd951876
JB
1633 .sort(
1634 (workerNodeA, workerNodeB) =>
1635 workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
1636 )
f201a0cd 1637 const sourceWorkerNode = workerNodes.find(
463226a4
JB
1638 (sourceWorkerNode, sourceWorkerNodeKey) =>
1639 sourceWorkerNode.info.ready &&
1640 sourceWorkerNodeKey !== workerNodeKey &&
1641 sourceWorkerNode.usage.tasks.queued > 0
f201a0cd
JB
1642 )
1643 if (sourceWorkerNode != null) {
72ae84a2 1644 const task = sourceWorkerNode.popTask() as Task<Data>
42c677c1 1645 this.handleTask(workerNodeKey, task)
f1f77f45 1646 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(workerNodeKey)
f201a0cd 1647 this.updateTaskStolenStatisticsWorkerUsage(
463226a4 1648 workerNodeKey,
f201a0cd
JB
1649 task.name as string
1650 )
463226a4 1651 return task
72695f86
JB
1652 }
1653 }
1654
9f95d5eb 1655 private readonly handleBackPressureEvent = (
e1c2dba7 1656 eventDetail: WorkerNodeEventDetail
9f95d5eb 1657 ): void => {
cb71d660
JB
1658 if (this.workerNodes.length <= 1) {
1659 return
1660 }
e1c2dba7 1661 const { workerId } = eventDetail
f778c355
JB
1662 const sizeOffset = 1
1663 if ((this.opts.tasksQueueOptions?.size as number) <= sizeOffset) {
68dbcdc0
JB
1664 return
1665 }
72695f86 1666 const sourceWorkerNode =
b5e75be8 1667 this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
72695f86 1668 const workerNodes = this.workerNodes
a6b3272b 1669 .slice()
72695f86
JB
1670 .sort(
1671 (workerNodeA, workerNodeB) =>
1672 workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
1673 )
1674 for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
1675 if (
0bc68267 1676 sourceWorkerNode.usage.tasks.queued > 0 &&
a6b3272b 1677 workerNode.info.ready &&
b5e75be8 1678 workerNode.info.id !== workerId &&
0bc68267 1679 workerNode.usage.tasks.queued <
f778c355 1680 (this.opts.tasksQueueOptions?.size as number) - sizeOffset
72695f86 1681 ) {
72ae84a2 1682 const task = sourceWorkerNode.popTask() as Task<Data>
42c677c1 1683 this.handleTask(workerNodeKey, task)
b1838604
JB
1684 this.updateTaskStolenStatisticsWorkerUsage(
1685 workerNodeKey,
b1838604
JB
1686 task.name as string
1687 )
10ecf8fd 1688 }
a2ed5053
JB
1689 }
1690 }
1691
be0676b3 1692 /**
fcd39179 1693 * This method is the message listener registered on each worker.
be0676b3 1694 */
3a776b6d
JB
1695 protected readonly workerMessageListener = (
1696 message: MessageValue<Response>
1697 ): void => {
fcd39179 1698 this.checkMessageWorkerId(message)
b641345c
JB
1699 const { workerId, ready, taskId, taskFunctionNames } = message
1700 if (ready != null && taskFunctionNames != null) {
fcd39179
JB
1701 // Worker ready response received from worker
1702 this.handleWorkerReadyResponse(message)
b641345c 1703 } else if (taskId != null) {
fcd39179
JB
1704 // Task execution response received from worker
1705 this.handleTaskExecutionResponse(message)
b641345c 1706 } else if (taskFunctionNames != null) {
fcd39179
JB
1707 // Task function names message received from worker
1708 this.getWorkerInfo(
b641345c
JB
1709 this.getWorkerNodeKeyByWorkerId(workerId)
1710 ).taskFunctionNames = taskFunctionNames
6b272951
JB
1711 }
1712 }
1713
10e2aa7e 1714 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
463226a4
JB
1715 const { workerId, ready, taskFunctionNames } = message
1716 if (ready === false) {
1717 throw new Error(`Worker ${workerId as number} failed to initialize`)
f05ed93c 1718 }
a5d15204 1719 const workerInfo = this.getWorkerInfo(
463226a4 1720 this.getWorkerNodeKeyByWorkerId(workerId)
46b0bb09 1721 )
463226a4
JB
1722 workerInfo.ready = ready as boolean
1723 workerInfo.taskFunctionNames = taskFunctionNames
55082af9
JB
1724 if (!this.readyEventEmitted && this.ready) {
1725 this.readyEventEmitted = true
1726 this.emitter?.emit(PoolEvents.ready, this.info)
2431bdb4 1727 }
6b272951
JB
1728 }
1729
1730 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
463226a4 1731 const { workerId, taskId, workerError, data } = message
5441aea6 1732 const promiseResponse = this.promiseResponseMap.get(taskId as string)
6b272951 1733 if (promiseResponse != null) {
f18fd12b 1734 const { resolve, reject, workerNodeKey, asyncResource } = promiseResponse
6703b9f4
JB
1735 if (workerError != null) {
1736 this.emitter?.emit(PoolEvents.taskError, workerError)
f18fd12b
JB
1737 asyncResource != null
1738 ? asyncResource.runInAsyncScope(
1739 reject,
1740 this.emitter,
1741 workerError.message
1742 )
1743 : reject(workerError.message)
6b272951 1744 } else {
f18fd12b
JB
1745 asyncResource != null
1746 ? asyncResource.runInAsyncScope(resolve, this.emitter, data)
1747 : resolve(data as Response)
6b272951 1748 }
f18fd12b 1749 asyncResource?.emitDestroy()
501aea93 1750 this.afterTaskExecutionHook(workerNodeKey, message)
f3a91bac 1751 this.workerChoiceStrategyContext.update(workerNodeKey)
5441aea6 1752 this.promiseResponseMap.delete(taskId as string)
463226a4
JB
1753 if (this.opts.enableTasksQueue === true) {
1754 const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks
1755 if (
1756 this.tasksQueueSize(workerNodeKey) > 0 &&
1757 workerNodeTasksUsage.executing <
1758 (this.opts.tasksQueueOptions?.concurrency as number)
1759 ) {
1760 this.executeTask(
1761 workerNodeKey,
1762 this.dequeueTask(workerNodeKey) as Task<Data>
1763 )
1764 }
1765 if (
1766 workerNodeTasksUsage.executing === 0 &&
1767 this.tasksQueueSize(workerNodeKey) === 0 &&
1768 workerNodeTasksUsage.sequentiallyStolen === 0
1769 ) {
e1c2dba7
JB
1770 this.workerNodes[workerNodeKey].emit('idleWorkerNode', {
1771 workerId: workerId as number,
1772 workerNodeKey
1773 })
463226a4 1774 }
be0676b3
APA
1775 }
1776 }
be0676b3 1777 }
7c0ba920 1778
a1763c54 1779 private checkAndEmitTaskExecutionEvents (): void {
33e6bb4c
JB
1780 if (this.busy) {
1781 this.emitter?.emit(PoolEvents.busy, this.info)
a1763c54
JB
1782 }
1783 }
1784
1785 private checkAndEmitTaskQueuingEvents (): void {
1786 if (this.hasBackPressure()) {
1787 this.emitter?.emit(PoolEvents.backPressure, this.info)
164d950a
JB
1788 }
1789 }
1790
33e6bb4c
JB
1791 private checkAndEmitDynamicWorkerCreationEvents (): void {
1792 if (this.type === PoolTypes.dynamic) {
1793 if (this.full) {
1794 this.emitter?.emit(PoolEvents.full, this.info)
1795 }
1796 }
1797 }
1798
8a1260a3 1799 /**
aa9eede8 1800 * Gets the worker information given its worker node key.
8a1260a3
JB
1801 *
1802 * @param workerNodeKey - The worker node key.
3f09ed9f 1803 * @returns The worker information.
8a1260a3 1804 */
46b0bb09 1805 protected getWorkerInfo (workerNodeKey: number): WorkerInfo {
dbfa7948 1806 return this.workerNodes[workerNodeKey]?.info
e221309a
JB
1807 }
1808
a05c10de 1809 /**
c3719753 1810 * Creates a worker node.
ea7a90d3 1811 *
c3719753 1812 * @returns The created worker node.
ea7a90d3 1813 */
c3719753 1814 private createWorkerNode (): IWorkerNode<Worker, Data> {
671d5154 1815 const workerNode = new WorkerNode<Worker, Data>(
c3719753
JB
1816 this.worker,
1817 this.filePath,
1818 {
1819 env: this.opts.env,
1820 workerOptions: this.opts.workerOptions,
1821 tasksQueueBackPressureSize:
1822 this.opts.tasksQueueOptions?.size ?? Math.pow(this.maxSize, 2)
1823 }
671d5154 1824 )
b97d82d8 1825 // Flag the worker node as ready at pool startup.
d2c73f82
JB
1826 if (this.starting) {
1827 workerNode.info.ready = true
1828 }
c3719753
JB
1829 return workerNode
1830 }
1831
1832 /**
1833 * Adds the given worker node in the pool worker nodes.
1834 *
1835 * @param workerNode - The worker node.
1836 * @returns The added worker node key.
1837 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1838 */
1839 private addWorkerNode (workerNode: IWorkerNode<Worker, Data>): number {
aa9eede8 1840 this.workerNodes.push(workerNode)
c3719753 1841 const workerNodeKey = this.workerNodes.indexOf(workerNode)
aa9eede8 1842 if (workerNodeKey === -1) {
86ed0598 1843 throw new Error('Worker added not found in worker nodes')
aa9eede8
JB
1844 }
1845 return workerNodeKey
ea7a90d3 1846 }
c923ce56 1847
51fe3d3c 1848 /**
c3719753 1849 * Removes the worker node associated to the give given worker from the pool worker nodes.
51fe3d3c 1850 *
f06e48d8 1851 * @param worker - The worker.
51fe3d3c 1852 */
416fd65c 1853 private removeWorkerNode (worker: Worker): void {
aad6fb64 1854 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1f68cede
JB
1855 if (workerNodeKey !== -1) {
1856 this.workerNodes.splice(workerNodeKey, 1)
1857 this.workerChoiceStrategyContext.remove(workerNodeKey)
1858 }
51fe3d3c 1859 }
adc3c320 1860
ae3ab61d
JB
1861 protected flagWorkerNodeAsNotReady (workerNodeKey: number): void {
1862 this.getWorkerInfo(workerNodeKey).ready = false
1863 }
1864
e2b31e32
JB
1865 /** @inheritDoc */
1866 public hasWorkerNodeBackPressure (workerNodeKey: number): boolean {
9e844245 1867 return (
e2b31e32
JB
1868 this.opts.enableTasksQueue === true &&
1869 this.workerNodes[workerNodeKey].hasBackPressure()
9e844245
JB
1870 )
1871 }
1872
1873 private hasBackPressure (): boolean {
1874 return (
1875 this.opts.enableTasksQueue === true &&
1876 this.workerNodes.findIndex(
041dc05b 1877 workerNode => !workerNode.hasBackPressure()
a1763c54 1878 ) === -1
9e844245 1879 )
e2b31e32
JB
1880 }
1881
b0a4db63 1882 /**
aa9eede8 1883 * Executes the given task on the worker given its worker node key.
b0a4db63 1884 *
aa9eede8 1885 * @param workerNodeKey - The worker node key.
b0a4db63
JB
1886 * @param task - The task to execute.
1887 */
2e81254d 1888 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1c6fe997 1889 this.beforeTaskExecutionHook(workerNodeKey, task)
bbfa38a2 1890 this.sendToWorker(workerNodeKey, task, task.transferList)
a1763c54 1891 this.checkAndEmitTaskExecutionEvents()
2e81254d
JB
1892 }
1893
f9f00b5f 1894 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
a1763c54
JB
1895 const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
1896 this.checkAndEmitTaskQueuingEvents()
1897 return tasksQueueSize
adc3c320
JB
1898 }
1899
416fd65c 1900 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
4b628b48 1901 return this.workerNodes[workerNodeKey].dequeueTask()
adc3c320
JB
1902 }
1903
416fd65c 1904 private tasksQueueSize (workerNodeKey: number): number {
4b628b48 1905 return this.workerNodes[workerNodeKey].tasksQueueSize()
df593701
JB
1906 }
1907
81c02522 1908 protected flushTasksQueue (workerNodeKey: number): void {
920278a2
JB
1909 while (this.tasksQueueSize(workerNodeKey) > 0) {
1910 this.executeTask(
1911 workerNodeKey,
1912 this.dequeueTask(workerNodeKey) as Task<Data>
1913 )
ff733df7 1914 }
4b628b48 1915 this.workerNodes[workerNodeKey].clearTasksQueue()
ff733df7
JB
1916 }
1917
ef41a6e6
JB
1918 private flushTasksQueues (): void {
1919 for (const [workerNodeKey] of this.workerNodes.entries()) {
1920 this.flushTasksQueue(workerNodeKey)
1921 }
1922 }
c97c7edb 1923}