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