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