docs: refine comments
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
2845f2a5 1import { randomUUID } from 'node:crypto'
62c15a68 2import { performance } from 'node:perf_hooks'
3d6dd312 3import { existsSync } from 'node:fs'
7d91a8cd 4import { type TransferListItem } from 'node:worker_threads'
5c4d16da
JB
5import type {
6 MessageValue,
7 PromiseResponseWrapper,
76d91ea0 8 Task
5c4d16da 9} from '../utility-types'
bbeadd16 10import {
ff128cc9 11 DEFAULT_TASK_NAME,
bbeadd16
JB
12 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
13 EMPTY_FUNCTION,
dc021bcc 14 average,
59317253 15 isKillBehavior,
0d80593b 16 isPlainObject,
90d6701c 17 max,
afe0d5bf 18 median,
90d6701c 19 min,
e4f20deb
JB
20 round,
21 updateMeasurementStatistics
bbeadd16 22} from '../utils'
59317253 23import { KillBehaviors } from '../worker/worker-options'
c4855468 24import {
65d7a1c9 25 type IPool,
7c5a1080 26 PoolEmitter,
c4855468 27 PoolEvents,
6b27d407 28 type PoolInfo,
c4855468 29 type PoolOptions,
6b27d407
JB
30 type PoolType,
31 PoolTypes,
4b628b48 32 type TasksQueueOptions
c4855468 33} from './pool'
bbfa38a2
JB
34import type {
35 IWorker,
36 IWorkerNode,
37 WorkerInfo,
38 WorkerType,
39 WorkerUsage
e102732c 40} from './worker'
a35560ba 41import {
008512c7 42 type MeasurementStatisticsRequirements,
f0d7f803 43 Measurements,
a35560ba 44 WorkerChoiceStrategies,
a20f0ba5
JB
45 type WorkerChoiceStrategy,
46 type WorkerChoiceStrategyOptions
bdaf31cd
JB
47} from './selection-strategies/selection-strategies-types'
48import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
92b1feaa 49import { version } from './version'
4b628b48 50import { WorkerNode } from './worker-node'
23ccf9d7 51
729c563d 52/**
ea7a90d3 53 * Base class that implements some shared logic for all poolifier pools.
729c563d 54 *
38e795c1 55 * @typeParam Worker - Type of worker which manages this pool.
e102732c
JB
56 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
57 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
729c563d 58 */
c97c7edb 59export abstract class AbstractPool<
f06e48d8 60 Worker extends IWorker,
d3c8a1a8
S
61 Data = unknown,
62 Response = unknown
c4855468 63> implements IPool<Worker, Data, Response> {
afc003b2 64 /** @inheritDoc */
4b628b48 65 public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
4a6952ff 66
afc003b2 67 /** @inheritDoc */
7c0ba920
JB
68 public readonly emitter?: PoolEmitter
69
be0676b3 70 /**
192566ec 71 * The task execution response promise map:
2740a743 72 * - `key`: The message id of each submitted task.
a3445496 73 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
be0676b3 74 *
a3445496 75 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 76 */
501aea93
JB
77 protected promiseResponseMap: Map<string, PromiseResponseWrapper<Response>> =
78 new Map<string, PromiseResponseWrapper<Response>>()
c97c7edb 79
a35560ba 80 /**
51fe3d3c 81 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba
S
82 */
83 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
84 Worker,
85 Data,
86 Response
a35560ba
S
87 >
88
8735b4e5
JB
89 /**
90 * Dynamic pool maximum size property placeholder.
91 */
92 protected readonly max?: number
93
15b176e0
JB
94 /**
95 * Whether the pool is started or not.
96 */
97 private started: boolean
47352846
JB
98 /**
99 * Whether the pool is starting or not.
100 */
101 private starting: boolean
afe0d5bf
JB
102 /**
103 * The start timestamp of the pool.
104 */
105 private readonly startTimestamp
106
729c563d
S
107 /**
108 * Constructs a new poolifier pool.
109 *
38e795c1 110 * @param numberOfWorkers - Number of workers that this pool should manage.
029715f0 111 * @param filePath - Path to the worker file.
38e795c1 112 * @param opts - Options for the pool.
729c563d 113 */
c97c7edb 114 public constructor (
b4213b7f
JB
115 protected readonly numberOfWorkers: number,
116 protected readonly filePath: string,
117 protected readonly opts: PoolOptions<Worker>
c97c7edb 118 ) {
78cea37e 119 if (!this.isMain()) {
04f45163 120 throw new Error(
8c6d4acf 121 'Cannot start a pool from a worker with the same type as the pool'
04f45163 122 )
c97c7edb 123 }
8d3782fa 124 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 125 this.checkFilePath(this.filePath)
7c0ba920 126 this.checkPoolOptions(this.opts)
1086026a 127
7254e419
JB
128 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
129 this.executeTask = this.executeTask.bind(this)
130 this.enqueueTask = this.enqueueTask.bind(this)
1086026a 131
6bd72cd0 132 if (this.opts.enableEvents === true) {
7c0ba920
JB
133 this.emitter = new PoolEmitter()
134 }
d59df138
JB
135 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
136 Worker,
137 Data,
138 Response
da309861
JB
139 >(
140 this,
141 this.opts.workerChoiceStrategy,
142 this.opts.workerChoiceStrategyOptions
143 )
b6b32453
JB
144
145 this.setupHook()
146
47352846 147 this.started = false
075e51d1 148 this.starting = false
47352846
JB
149 if (this.opts.startWorkers === true) {
150 this.start()
151 }
afe0d5bf
JB
152
153 this.startTimestamp = performance.now()
c97c7edb
S
154 }
155
a35560ba 156 private checkFilePath (filePath: string): void {
ffcbbad8
JB
157 if (
158 filePath == null ||
3d6dd312 159 typeof filePath !== 'string' ||
ffcbbad8
JB
160 (typeof filePath === 'string' && filePath.trim().length === 0)
161 ) {
c510fea7
APA
162 throw new Error('Please specify a file with a worker implementation')
163 }
3d6dd312
JB
164 if (!existsSync(filePath)) {
165 throw new Error(`Cannot find the worker file '${filePath}'`)
166 }
c510fea7
APA
167 }
168
8d3782fa
JB
169 private checkNumberOfWorkers (numberOfWorkers: number): void {
170 if (numberOfWorkers == null) {
171 throw new Error(
172 'Cannot instantiate a pool without specifying the number of workers'
173 )
78cea37e 174 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 175 throw new TypeError(
0d80593b 176 'Cannot instantiate a pool with a non safe integer number of workers'
8d3782fa
JB
177 )
178 } else if (numberOfWorkers < 0) {
473c717a 179 throw new RangeError(
8d3782fa
JB
180 'Cannot instantiate a pool with a negative number of workers'
181 )
6b27d407 182 } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
2431bdb4
JB
183 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
184 }
185 }
186
187 protected checkDynamicPoolSize (min: number, max: number): void {
079de991 188 if (this.type === PoolTypes.dynamic) {
a5ed75b7 189 if (max == null) {
e695d66f 190 throw new TypeError(
a5ed75b7
JB
191 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
192 )
193 } else if (!Number.isSafeInteger(max)) {
2761efb4
JB
194 throw new TypeError(
195 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
196 )
197 } else if (min > max) {
079de991
JB
198 throw new RangeError(
199 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
200 )
b97d82d8 201 } else if (max === 0) {
079de991 202 throw new RangeError(
d640b48b 203 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
079de991
JB
204 )
205 } else if (min === max) {
206 throw new RangeError(
207 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
208 )
209 }
8d3782fa
JB
210 }
211 }
212
7c0ba920 213 private checkPoolOptions (opts: PoolOptions<Worker>): void {
0d80593b 214 if (isPlainObject(opts)) {
47352846 215 this.opts.startWorkers = opts.startWorkers ?? true
0d80593b
JB
216 this.opts.workerChoiceStrategy =
217 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
218 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
8990357d
JB
219 this.opts.workerChoiceStrategyOptions = {
220 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
221 ...opts.workerChoiceStrategyOptions
222 }
49be33fe
JB
223 this.checkValidWorkerChoiceStrategyOptions(
224 this.opts.workerChoiceStrategyOptions
225 )
1f68cede 226 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
0d80593b
JB
227 this.opts.enableEvents = opts.enableEvents ?? true
228 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
229 if (this.opts.enableTasksQueue) {
230 this.checkValidTasksQueueOptions(
231 opts.tasksQueueOptions as TasksQueueOptions
232 )
233 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
234 opts.tasksQueueOptions as TasksQueueOptions
235 )
236 }
237 } else {
238 throw new TypeError('Invalid pool options: must be a plain object')
7171d33f 239 }
aee46736
JB
240 }
241
242 private checkValidWorkerChoiceStrategy (
243 workerChoiceStrategy: WorkerChoiceStrategy
244 ): void {
245 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
b529c323 246 throw new Error(
aee46736 247 `Invalid worker choice strategy '${workerChoiceStrategy}'`
b529c323
JB
248 )
249 }
7c0ba920
JB
250 }
251
0d80593b
JB
252 private checkValidWorkerChoiceStrategyOptions (
253 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
254 ): void {
255 if (!isPlainObject(workerChoiceStrategyOptions)) {
256 throw new TypeError(
257 'Invalid worker choice strategy options: must be a plain object'
258 )
259 }
8990357d 260 if (
8c0b113f
JB
261 workerChoiceStrategyOptions.retries != null &&
262 !Number.isSafeInteger(workerChoiceStrategyOptions.retries)
8990357d
JB
263 ) {
264 throw new TypeError(
8c0b113f 265 'Invalid worker choice strategy options: retries must be an integer'
8990357d
JB
266 )
267 }
268 if (
8c0b113f
JB
269 workerChoiceStrategyOptions.retries != null &&
270 workerChoiceStrategyOptions.retries < 0
8990357d
JB
271 ) {
272 throw new RangeError(
8c0b113f 273 `Invalid worker choice strategy options: retries '${workerChoiceStrategyOptions.retries}' must be greater or equal than zero`
8990357d
JB
274 )
275 }
49be33fe
JB
276 if (
277 workerChoiceStrategyOptions.weights != null &&
6b27d407 278 Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
49be33fe
JB
279 ) {
280 throw new Error(
281 'Invalid worker choice strategy options: must have a weight for each worker node'
282 )
283 }
f0d7f803
JB
284 if (
285 workerChoiceStrategyOptions.measurement != null &&
286 !Object.values(Measurements).includes(
287 workerChoiceStrategyOptions.measurement
288 )
289 ) {
290 throw new Error(
291 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
292 )
293 }
0d80593b
JB
294 }
295
a20f0ba5 296 private checkValidTasksQueueOptions (
76d91ea0 297 tasksQueueOptions: TasksQueueOptions
a20f0ba5 298 ): void {
0d80593b
JB
299 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
300 throw new TypeError('Invalid tasks queue options: must be a plain object')
301 }
f0d7f803 302 if (
b7d085c4
JB
303 tasksQueueOptions?.concurrency != null &&
304 !Number.isSafeInteger(tasksQueueOptions?.concurrency)
f0d7f803
JB
305 ) {
306 throw new TypeError(
20c6f652 307 'Invalid worker node tasks concurrency: must be an integer'
f0d7f803
JB
308 )
309 }
310 if (
b7d085c4
JB
311 tasksQueueOptions?.concurrency != null &&
312 tasksQueueOptions?.concurrency <= 0
f0d7f803 313 ) {
e695d66f 314 throw new RangeError(
b7d085c4 315 `Invalid worker node tasks concurrency: ${tasksQueueOptions?.concurrency} is a negative integer or zero`
20c6f652
JB
316 )
317 }
20c6f652 318 if (
b7d085c4
JB
319 tasksQueueOptions?.size != null &&
320 !Number.isSafeInteger(tasksQueueOptions?.size)
20c6f652 321 ) {
ff3f866a 322 throw new TypeError(
68dbcdc0 323 'Invalid worker node tasks queue size: must be an integer'
ff3f866a
JB
324 )
325 }
b7d085c4 326 if (tasksQueueOptions?.size != null && tasksQueueOptions?.size <= 0) {
20c6f652 327 throw new RangeError(
b7d085c4 328 `Invalid worker node tasks queue size: ${tasksQueueOptions?.size} is a negative integer or zero`
a20f0ba5
JB
329 )
330 }
331 }
332
08f3f44c 333 /** @inheritDoc */
6b27d407
JB
334 public get info (): PoolInfo {
335 return {
23ccf9d7 336 version,
6b27d407 337 type: this.type,
184855e6 338 worker: this.worker,
47352846 339 started: this.started,
2431bdb4
JB
340 ready: this.ready,
341 strategy: this.opts.workerChoiceStrategy as WorkerChoiceStrategy,
6b27d407
JB
342 minSize: this.minSize,
343 maxSize: this.maxSize,
c05f0d50
JB
344 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
345 .runTime.aggregate &&
1305e9a8
JB
346 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
347 .waitTime.aggregate && { utilization: round(this.utilization) }),
6b27d407
JB
348 workerNodes: this.workerNodes.length,
349 idleWorkerNodes: this.workerNodes.reduce(
350 (accumulator, workerNode) =>
f59e1027 351 workerNode.usage.tasks.executing === 0
a4e07f72
JB
352 ? accumulator + 1
353 : accumulator,
6b27d407
JB
354 0
355 ),
356 busyWorkerNodes: this.workerNodes.reduce(
357 (accumulator, workerNode) =>
f59e1027 358 workerNode.usage.tasks.executing > 0 ? accumulator + 1 : accumulator,
6b27d407
JB
359 0
360 ),
a4e07f72 361 executedTasks: this.workerNodes.reduce(
6b27d407 362 (accumulator, workerNode) =>
f59e1027 363 accumulator + workerNode.usage.tasks.executed,
a4e07f72
JB
364 0
365 ),
366 executingTasks: this.workerNodes.reduce(
367 (accumulator, workerNode) =>
f59e1027 368 accumulator + workerNode.usage.tasks.executing,
6b27d407
JB
369 0
370 ),
daf86646
JB
371 ...(this.opts.enableTasksQueue === true && {
372 queuedTasks: this.workerNodes.reduce(
373 (accumulator, workerNode) =>
374 accumulator + workerNode.usage.tasks.queued,
375 0
376 )
377 }),
378 ...(this.opts.enableTasksQueue === true && {
379 maxQueuedTasks: this.workerNodes.reduce(
380 (accumulator, workerNode) =>
381 accumulator + (workerNode.usage.tasks?.maxQueued ?? 0),
382 0
383 )
384 }),
a1763c54
JB
385 ...(this.opts.enableTasksQueue === true && {
386 backPressure: this.hasBackPressure()
387 }),
68cbdc84
JB
388 ...(this.opts.enableTasksQueue === true && {
389 stolenTasks: this.workerNodes.reduce(
390 (accumulator, workerNode) =>
391 accumulator + workerNode.usage.tasks.stolen,
392 0
393 )
394 }),
a4e07f72
JB
395 failedTasks: this.workerNodes.reduce(
396 (accumulator, workerNode) =>
f59e1027 397 accumulator + workerNode.usage.tasks.failed,
a4e07f72 398 0
1dcf8b7b
JB
399 ),
400 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
401 .runTime.aggregate && {
402 runTime: {
98e72cda 403 minimum: round(
90d6701c 404 min(
98e72cda 405 ...this.workerNodes.map(
041dc05b 406 workerNode => workerNode.usage.runTime?.minimum ?? Infinity
98e72cda 407 )
1dcf8b7b
JB
408 )
409 ),
98e72cda 410 maximum: round(
90d6701c 411 max(
98e72cda 412 ...this.workerNodes.map(
041dc05b 413 workerNode => workerNode.usage.runTime?.maximum ?? -Infinity
98e72cda 414 )
1dcf8b7b 415 )
98e72cda 416 ),
3baa0837
JB
417 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
418 .runTime.average && {
419 average: round(
420 average(
421 this.workerNodes.reduce<number[]>(
422 (accumulator, workerNode) =>
423 accumulator.concat(workerNode.usage.runTime.history),
424 []
425 )
98e72cda 426 )
dc021bcc 427 )
3baa0837 428 }),
98e72cda
JB
429 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
430 .runTime.median && {
431 median: round(
432 median(
3baa0837
JB
433 this.workerNodes.reduce<number[]>(
434 (accumulator, workerNode) =>
435 accumulator.concat(workerNode.usage.runTime.history),
436 []
98e72cda
JB
437 )
438 )
439 )
440 })
1dcf8b7b
JB
441 }
442 }),
443 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
444 .waitTime.aggregate && {
445 waitTime: {
98e72cda 446 minimum: round(
90d6701c 447 min(
98e72cda 448 ...this.workerNodes.map(
041dc05b 449 workerNode => workerNode.usage.waitTime?.minimum ?? Infinity
98e72cda 450 )
1dcf8b7b
JB
451 )
452 ),
98e72cda 453 maximum: round(
90d6701c 454 max(
98e72cda 455 ...this.workerNodes.map(
041dc05b 456 workerNode => workerNode.usage.waitTime?.maximum ?? -Infinity
98e72cda 457 )
1dcf8b7b 458 )
98e72cda 459 ),
3baa0837
JB
460 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
461 .waitTime.average && {
462 average: round(
463 average(
464 this.workerNodes.reduce<number[]>(
465 (accumulator, workerNode) =>
466 accumulator.concat(workerNode.usage.waitTime.history),
467 []
468 )
98e72cda 469 )
dc021bcc 470 )
3baa0837 471 }),
98e72cda
JB
472 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
473 .waitTime.median && {
474 median: round(
475 median(
3baa0837
JB
476 this.workerNodes.reduce<number[]>(
477 (accumulator, workerNode) =>
478 accumulator.concat(workerNode.usage.waitTime.history),
479 []
98e72cda
JB
480 )
481 )
482 )
483 })
1dcf8b7b
JB
484 }
485 })
6b27d407
JB
486 }
487 }
08f3f44c 488
aa9eede8
JB
489 /**
490 * The pool readiness boolean status.
491 */
2431bdb4
JB
492 private get ready (): boolean {
493 return (
b97d82d8
JB
494 this.workerNodes.reduce(
495 (accumulator, workerNode) =>
496 !workerNode.info.dynamic && workerNode.info.ready
497 ? accumulator + 1
498 : accumulator,
499 0
500 ) >= this.minSize
2431bdb4
JB
501 )
502 }
503
afe0d5bf 504 /**
aa9eede8 505 * The approximate pool utilization.
afe0d5bf
JB
506 *
507 * @returns The pool utilization.
508 */
509 private get utilization (): number {
8e5ca040 510 const poolTimeCapacity =
fe7d90db 511 (performance.now() - this.startTimestamp) * this.maxSize
afe0d5bf
JB
512 const totalTasksRunTime = this.workerNodes.reduce(
513 (accumulator, workerNode) =>
71514351 514 accumulator + (workerNode.usage.runTime?.aggregate ?? 0),
afe0d5bf
JB
515 0
516 )
517 const totalTasksWaitTime = this.workerNodes.reduce(
518 (accumulator, workerNode) =>
71514351 519 accumulator + (workerNode.usage.waitTime?.aggregate ?? 0),
afe0d5bf
JB
520 0
521 )
8e5ca040 522 return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
afe0d5bf
JB
523 }
524
8881ae32 525 /**
aa9eede8 526 * The pool type.
8881ae32
JB
527 *
528 * If it is `'dynamic'`, it provides the `max` property.
529 */
530 protected abstract get type (): PoolType
531
184855e6 532 /**
aa9eede8 533 * The worker type.
184855e6
JB
534 */
535 protected abstract get worker (): WorkerType
536
c2ade475 537 /**
aa9eede8 538 * The pool minimum size.
c2ade475 539 */
8735b4e5
JB
540 protected get minSize (): number {
541 return this.numberOfWorkers
542 }
ff733df7
JB
543
544 /**
aa9eede8 545 * The pool maximum size.
ff733df7 546 */
8735b4e5
JB
547 protected get maxSize (): number {
548 return this.max ?? this.numberOfWorkers
549 }
a35560ba 550
6b813701
JB
551 /**
552 * Checks if the worker id sent in the received message from a worker is valid.
553 *
554 * @param message - The received message.
555 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
556 */
21f710aa 557 private checkMessageWorkerId (message: MessageValue<Response>): void {
310de0aa
JB
558 if (message.workerId == null) {
559 throw new Error('Worker message received without worker id')
560 } else if (
21f710aa 561 message.workerId != null &&
aad6fb64 562 this.getWorkerNodeKeyByWorkerId(message.workerId) === -1
21f710aa
JB
563 ) {
564 throw new Error(
565 `Worker message received from unknown worker '${message.workerId}'`
566 )
567 }
568 }
569
ffcbbad8 570 /**
f06e48d8 571 * Gets the given worker its worker node key.
ffcbbad8
JB
572 *
573 * @param worker - The worker.
f59e1027 574 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
ffcbbad8 575 */
aad6fb64 576 private getWorkerNodeKeyByWorker (worker: Worker): number {
f06e48d8 577 return this.workerNodes.findIndex(
041dc05b 578 workerNode => workerNode.worker === worker
f06e48d8 579 )
bf9549ae
JB
580 }
581
aa9eede8
JB
582 /**
583 * Gets the worker node key given its worker id.
584 *
585 * @param workerId - The worker id.
aad6fb64 586 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
aa9eede8 587 */
aad6fb64
JB
588 private getWorkerNodeKeyByWorkerId (workerId: number): number {
589 return this.workerNodes.findIndex(
041dc05b 590 workerNode => workerNode.info.id === workerId
aad6fb64 591 )
aa9eede8
JB
592 }
593
afc003b2 594 /** @inheritDoc */
a35560ba 595 public setWorkerChoiceStrategy (
59219cbb
JB
596 workerChoiceStrategy: WorkerChoiceStrategy,
597 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 598 ): void {
aee46736 599 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
b98ec2e6 600 this.opts.workerChoiceStrategy = workerChoiceStrategy
b6b32453
JB
601 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
602 this.opts.workerChoiceStrategy
603 )
604 if (workerChoiceStrategyOptions != null) {
605 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
606 }
aa9eede8 607 for (const [workerNodeKey, workerNode] of this.workerNodes.entries()) {
4b628b48 608 workerNode.resetUsage()
9edb9717 609 this.sendStatisticsMessageToWorker(workerNodeKey)
59219cbb 610 }
a20f0ba5
JB
611 }
612
613 /** @inheritDoc */
614 public setWorkerChoiceStrategyOptions (
615 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
616 ): void {
0d80593b 617 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
8990357d
JB
618 this.opts.workerChoiceStrategyOptions = {
619 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
620 ...workerChoiceStrategyOptions
621 }
a20f0ba5
JB
622 this.workerChoiceStrategyContext.setOptions(
623 this.opts.workerChoiceStrategyOptions
a35560ba
S
624 )
625 }
626
a20f0ba5 627 /** @inheritDoc */
8f52842f
JB
628 public enableTasksQueue (
629 enable: boolean,
630 tasksQueueOptions?: TasksQueueOptions
631 ): void {
a20f0ba5 632 if (this.opts.enableTasksQueue === true && !enable) {
ef41a6e6 633 this.flushTasksQueues()
a20f0ba5
JB
634 }
635 this.opts.enableTasksQueue = enable
8f52842f 636 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
a20f0ba5
JB
637 }
638
639 /** @inheritDoc */
8f52842f 640 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
a20f0ba5 641 if (this.opts.enableTasksQueue === true) {
8f52842f
JB
642 this.checkValidTasksQueueOptions(tasksQueueOptions)
643 this.opts.tasksQueueOptions =
644 this.buildTasksQueueOptions(tasksQueueOptions)
5b49e864 645 this.setTasksQueueSize(this.opts.tasksQueueOptions.size as number)
5baee0d7 646 } else if (this.opts.tasksQueueOptions != null) {
a20f0ba5
JB
647 delete this.opts.tasksQueueOptions
648 }
649 }
650
5b49e864 651 private setTasksQueueSize (size: number): void {
20c6f652 652 for (const workerNode of this.workerNodes) {
ff3f866a 653 workerNode.tasksQueueBackPressureSize = size
20c6f652
JB
654 }
655 }
656
a20f0ba5
JB
657 private buildTasksQueueOptions (
658 tasksQueueOptions: TasksQueueOptions
659 ): TasksQueueOptions {
660 return {
20c6f652 661 ...{
ff3f866a 662 size: Math.pow(this.maxSize, 2),
47352846 663 concurrency: 1,
dbd73092 664 taskStealing: true,
47352846 665 tasksStealingOnBackPressure: true
20c6f652
JB
666 },
667 ...tasksQueueOptions
a20f0ba5
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 )
702 } else {
703 return (
704 this.workerNodes.findIndex(
041dc05b 705 workerNode =>
3d76750a
JB
706 workerNode.info.ready && workerNode.usage.tasks.executing === 0
707 ) === -1
708 )
709 }
cb70b19d
JB
710 }
711
90d7d101
JB
712 /** @inheritDoc */
713 public listTaskFunctions (): string[] {
f2dbbf95
JB
714 for (const workerNode of this.workerNodes) {
715 if (
716 Array.isArray(workerNode.info.taskFunctions) &&
717 workerNode.info.taskFunctions.length > 0
718 ) {
719 return workerNode.info.taskFunctions
720 }
90d7d101 721 }
f2dbbf95 722 return []
90d7d101
JB
723 }
724
375f7504
JB
725 private shallExecuteTask (workerNodeKey: number): boolean {
726 return (
727 this.tasksQueueSize(workerNodeKey) === 0 &&
728 this.workerNodes[workerNodeKey].usage.tasks.executing <
729 (this.opts.tasksQueueOptions?.concurrency as number)
730 )
731 }
732
afc003b2 733 /** @inheritDoc */
7d91a8cd
JB
734 public async execute (
735 data?: Data,
736 name?: string,
737 transferList?: TransferListItem[]
738 ): Promise<Response> {
52b71763 739 return await new Promise<Response>((resolve, reject) => {
15b176e0 740 if (!this.started) {
47352846 741 reject(new Error('Cannot execute a task on not started pool'))
9d2d0da1 742 return
15b176e0 743 }
7d91a8cd
JB
744 if (name != null && typeof name !== 'string') {
745 reject(new TypeError('name argument must be a string'))
9d2d0da1 746 return
7d91a8cd 747 }
90d7d101
JB
748 if (
749 name != null &&
750 typeof name === 'string' &&
751 name.trim().length === 0
752 ) {
f58b60b9 753 reject(new TypeError('name argument must not be an empty string'))
9d2d0da1 754 return
90d7d101 755 }
b558f6b5
JB
756 if (transferList != null && !Array.isArray(transferList)) {
757 reject(new TypeError('transferList argument must be an array'))
9d2d0da1 758 return
b558f6b5
JB
759 }
760 const timestamp = performance.now()
761 const workerNodeKey = this.chooseWorkerNode()
501aea93 762 const task: Task<Data> = {
52b71763
JB
763 name: name ?? DEFAULT_TASK_NAME,
764 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
765 data: data ?? ({} as Data),
7d91a8cd 766 transferList,
52b71763 767 timestamp,
1a28f967 768 workerId: this.getWorkerInfo(workerNodeKey).id as number,
7629bdf1 769 taskId: randomUUID()
52b71763 770 }
7629bdf1 771 this.promiseResponseMap.set(task.taskId as string, {
2e81254d
JB
772 resolve,
773 reject,
501aea93 774 workerNodeKey
2e81254d 775 })
52b71763 776 if (
4e377863
JB
777 this.opts.enableTasksQueue === false ||
778 (this.opts.enableTasksQueue === true &&
375f7504 779 this.shallExecuteTask(workerNodeKey))
52b71763 780 ) {
501aea93 781 this.executeTask(workerNodeKey, task)
4e377863
JB
782 } else {
783 this.enqueueTask(workerNodeKey, task)
52b71763 784 }
2e81254d 785 })
280c2a77 786 }
c97c7edb 787
47352846
JB
788 /** @inheritdoc */
789 public start (): void {
790 this.starting = true
791 while (
792 this.workerNodes.reduce(
793 (accumulator, workerNode) =>
794 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
795 0
796 ) < this.numberOfWorkers
797 ) {
798 this.createAndSetupWorkerNode()
799 }
800 this.starting = false
801 this.started = true
802 }
803
afc003b2 804 /** @inheritDoc */
c97c7edb 805 public async destroy (): Promise<void> {
1fbcaa7c 806 await Promise.all(
81c02522 807 this.workerNodes.map(async (_, workerNodeKey) => {
aa9eede8 808 await this.destroyWorkerNode(workerNodeKey)
1fbcaa7c
JB
809 })
810 )
33e6bb4c 811 this.emitter?.emit(PoolEvents.destroy, this.info)
15b176e0 812 this.started = false
c97c7edb
S
813 }
814
1e3214b6
JB
815 protected async sendKillMessageToWorker (
816 workerNodeKey: number,
817 workerId: number
818 ): Promise<void> {
9edb9717 819 await new Promise<void>((resolve, reject) => {
041dc05b 820 this.registerWorkerMessageListener(workerNodeKey, message => {
1e3214b6
JB
821 if (message.kill === 'success') {
822 resolve()
823 } else if (message.kill === 'failure') {
e1af34e6 824 reject(new Error(`Worker ${workerId} kill message handling failed`))
1e3214b6
JB
825 }
826 })
9edb9717 827 this.sendToWorker(workerNodeKey, { kill: true, workerId })
1e3214b6 828 })
1e3214b6
JB
829 }
830
4a6952ff 831 /**
aa9eede8 832 * Terminates the worker node given its worker node key.
4a6952ff 833 *
aa9eede8 834 * @param workerNodeKey - The worker node key.
4a6952ff 835 */
81c02522 836 protected abstract destroyWorkerNode (workerNodeKey: number): Promise<void>
c97c7edb 837
729c563d 838 /**
6677a3d3
JB
839 * Setup hook to execute code before worker nodes are created in the abstract constructor.
840 * Can be overridden.
afc003b2
JB
841 *
842 * @virtual
729c563d 843 */
280c2a77 844 protected setupHook (): void {
965df41c 845 /* Intentionally empty */
280c2a77 846 }
c97c7edb 847
729c563d 848 /**
280c2a77
S
849 * Should return whether the worker is the main worker or not.
850 */
851 protected abstract isMain (): boolean
852
853 /**
2e81254d 854 * Hook executed before the worker task execution.
bf9549ae 855 * Can be overridden.
729c563d 856 *
f06e48d8 857 * @param workerNodeKey - The worker node key.
1c6fe997 858 * @param task - The task to execute.
729c563d 859 */
1c6fe997
JB
860 protected beforeTaskExecutionHook (
861 workerNodeKey: number,
862 task: Task<Data>
863 ): void {
94407def
JB
864 if (this.workerNodes[workerNodeKey]?.usage != null) {
865 const workerUsage = this.workerNodes[workerNodeKey].usage
866 ++workerUsage.tasks.executing
867 this.updateWaitTimeWorkerUsage(workerUsage, task)
868 }
869 if (
870 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
871 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
872 task.name as string
873 ) != null
874 ) {
db0e38ee 875 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 876 workerNodeKey
db0e38ee 877 ].getTaskFunctionWorkerUsage(task.name as string) as WorkerUsage
5623b8d5
JB
878 ++taskFunctionWorkerUsage.tasks.executing
879 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage, task)
b558f6b5 880 }
c97c7edb
S
881 }
882
c01733f1 883 /**
2e81254d 884 * Hook executed after the worker task execution.
bf9549ae 885 * Can be overridden.
c01733f1 886 *
501aea93 887 * @param workerNodeKey - The worker node key.
38e795c1 888 * @param message - The received message.
c01733f1 889 */
2e81254d 890 protected afterTaskExecutionHook (
501aea93 891 workerNodeKey: number,
2740a743 892 message: MessageValue<Response>
bf9549ae 893 ): void {
94407def
JB
894 if (this.workerNodes[workerNodeKey]?.usage != null) {
895 const workerUsage = this.workerNodes[workerNodeKey].usage
896 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
897 this.updateRunTimeWorkerUsage(workerUsage, message)
898 this.updateEluWorkerUsage(workerUsage, message)
899 }
900 if (
901 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
902 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
5623b8d5 903 message.taskPerformance?.name as string
94407def
JB
904 ) != null
905 ) {
db0e38ee 906 const taskFunctionWorkerUsage = this.workerNodes[
b558f6b5 907 workerNodeKey
db0e38ee 908 ].getTaskFunctionWorkerUsage(
0628755c 909 message.taskPerformance?.name as string
b558f6b5 910 ) as WorkerUsage
db0e38ee
JB
911 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
912 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage, message)
913 this.updateEluWorkerUsage(taskFunctionWorkerUsage, message)
b558f6b5
JB
914 }
915 }
916
db0e38ee
JB
917 /**
918 * Whether the worker node shall update its task function worker usage or not.
919 *
920 * @param workerNodeKey - The worker node key.
921 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
922 */
923 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
a5d15204 924 const workerInfo = this.getWorkerInfo(workerNodeKey)
b558f6b5 925 return (
94407def 926 workerInfo != null &&
a5d15204 927 Array.isArray(workerInfo.taskFunctions) &&
db0e38ee 928 workerInfo.taskFunctions.length > 2
b558f6b5 929 )
f1c06930
JB
930 }
931
932 private updateTaskStatisticsWorkerUsage (
933 workerUsage: WorkerUsage,
934 message: MessageValue<Response>
935 ): void {
a4e07f72 936 const workerTaskStatistics = workerUsage.tasks
5bb5be17
JB
937 if (
938 workerTaskStatistics.executing != null &&
939 workerTaskStatistics.executing > 0
940 ) {
941 --workerTaskStatistics.executing
5bb5be17 942 }
98e72cda
JB
943 if (message.taskError == null) {
944 ++workerTaskStatistics.executed
945 } else {
a4e07f72 946 ++workerTaskStatistics.failed
2740a743 947 }
f8eb0a2a
JB
948 }
949
a4e07f72
JB
950 private updateRunTimeWorkerUsage (
951 workerUsage: WorkerUsage,
f8eb0a2a
JB
952 message: MessageValue<Response>
953 ): void {
dc021bcc
JB
954 if (message.taskError != null) {
955 return
956 }
e4f20deb
JB
957 updateMeasurementStatistics(
958 workerUsage.runTime,
959 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime,
dc021bcc 960 message.taskPerformance?.runTime ?? 0
e4f20deb 961 )
f8eb0a2a
JB
962 }
963
a4e07f72
JB
964 private updateWaitTimeWorkerUsage (
965 workerUsage: WorkerUsage,
1c6fe997 966 task: Task<Data>
f8eb0a2a 967 ): void {
1c6fe997
JB
968 const timestamp = performance.now()
969 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
e4f20deb
JB
970 updateMeasurementStatistics(
971 workerUsage.waitTime,
972 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime,
dc021bcc 973 taskWaitTime
e4f20deb 974 )
c01733f1 975 }
976
a4e07f72 977 private updateEluWorkerUsage (
5df69fab 978 workerUsage: WorkerUsage,
62c15a68
JB
979 message: MessageValue<Response>
980 ): void {
dc021bcc
JB
981 if (message.taskError != null) {
982 return
983 }
008512c7
JB
984 const eluTaskStatisticsRequirements: MeasurementStatisticsRequirements =
985 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
e4f20deb
JB
986 updateMeasurementStatistics(
987 workerUsage.elu.active,
008512c7 988 eluTaskStatisticsRequirements,
dc021bcc 989 message.taskPerformance?.elu?.active ?? 0
e4f20deb
JB
990 )
991 updateMeasurementStatistics(
992 workerUsage.elu.idle,
008512c7 993 eluTaskStatisticsRequirements,
dc021bcc 994 message.taskPerformance?.elu?.idle ?? 0
e4f20deb 995 )
008512c7 996 if (eluTaskStatisticsRequirements.aggregate) {
f7510105 997 if (message.taskPerformance?.elu != null) {
f7510105
JB
998 if (workerUsage.elu.utilization != null) {
999 workerUsage.elu.utilization =
1000 (workerUsage.elu.utilization +
1001 message.taskPerformance.elu.utilization) /
1002 2
1003 } else {
1004 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
1005 }
62c15a68
JB
1006 }
1007 }
1008 }
1009
280c2a77 1010 /**
f06e48d8 1011 * Chooses a worker node for the next task.
280c2a77 1012 *
6c6afb84 1013 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
280c2a77 1014 *
aa9eede8 1015 * @returns The chosen worker node key
280c2a77 1016 */
6c6afb84 1017 private chooseWorkerNode (): number {
930dcf12 1018 if (this.shallCreateDynamicWorker()) {
aa9eede8 1019 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
6c6afb84 1020 if (
b1aae695 1021 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
6c6afb84 1022 ) {
aa9eede8 1023 return workerNodeKey
6c6afb84 1024 }
17393ac8 1025 }
930dcf12
JB
1026 return this.workerChoiceStrategyContext.execute()
1027 }
1028
6c6afb84
JB
1029 /**
1030 * Conditions for dynamic worker creation.
1031 *
1032 * @returns Whether to create a dynamic worker or not.
1033 */
1034 private shallCreateDynamicWorker (): boolean {
930dcf12 1035 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
c97c7edb
S
1036 }
1037
280c2a77 1038 /**
aa9eede8 1039 * Sends a message to worker given its worker node key.
280c2a77 1040 *
aa9eede8 1041 * @param workerNodeKey - The worker node key.
38e795c1 1042 * @param message - The message.
7d91a8cd 1043 * @param transferList - The optional array of transferable objects.
280c2a77
S
1044 */
1045 protected abstract sendToWorker (
aa9eede8 1046 workerNodeKey: number,
7d91a8cd
JB
1047 message: MessageValue<Data>,
1048 transferList?: TransferListItem[]
280c2a77
S
1049 ): void
1050
729c563d 1051 /**
41344292 1052 * Creates a new worker.
6c6afb84
JB
1053 *
1054 * @returns Newly created worker.
729c563d 1055 */
280c2a77 1056 protected abstract createWorker (): Worker
c97c7edb 1057
4a6952ff 1058 /**
aa9eede8 1059 * Creates a new, completely set up worker node.
4a6952ff 1060 *
aa9eede8 1061 * @returns New, completely set up worker node key.
4a6952ff 1062 */
aa9eede8 1063 protected createAndSetupWorkerNode (): number {
bdacc2d2 1064 const worker = this.createWorker()
280c2a77 1065
fd04474e 1066 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
35cf1c03 1067 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba 1068 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
041dc05b 1069 worker.on('error', error => {
aad6fb64 1070 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
46b0bb09 1071 const workerInfo = this.getWorkerInfo(workerNodeKey)
9b106837 1072 workerInfo.ready = false
0dc838e3 1073 this.workerNodes[workerNodeKey].closeChannel()
2a69b8c5 1074 this.emitter?.emit(PoolEvents.error, error)
15b176e0
JB
1075 if (
1076 this.opts.restartWorkerOnError === true &&
b6bfca01
JB
1077 this.started &&
1078 !this.starting
15b176e0 1079 ) {
9b106837 1080 if (workerInfo.dynamic) {
aa9eede8 1081 this.createAndSetupDynamicWorkerNode()
8a1260a3 1082 } else {
aa9eede8 1083 this.createAndSetupWorkerNode()
8a1260a3 1084 }
5baee0d7 1085 }
19dbc45b 1086 if (this.opts.enableTasksQueue === true) {
9b106837 1087 this.redistributeQueuedTasks(workerNodeKey)
19dbc45b 1088 }
5baee0d7 1089 })
a35560ba 1090 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 1091 worker.once('exit', () => {
f06e48d8 1092 this.removeWorkerNode(worker)
a974afa6 1093 })
280c2a77 1094
aa9eede8 1095 const workerNodeKey = this.addWorkerNode(worker)
280c2a77 1096
aa9eede8 1097 this.afterWorkerNodeSetup(workerNodeKey)
280c2a77 1098
aa9eede8 1099 return workerNodeKey
c97c7edb 1100 }
be0676b3 1101
930dcf12 1102 /**
aa9eede8 1103 * Creates a new, completely set up dynamic worker node.
930dcf12 1104 *
aa9eede8 1105 * @returns New, completely set up dynamic worker node key.
930dcf12 1106 */
aa9eede8
JB
1107 protected createAndSetupDynamicWorkerNode (): number {
1108 const workerNodeKey = this.createAndSetupWorkerNode()
041dc05b 1109 this.registerWorkerMessageListener(workerNodeKey, message => {
aa9eede8
JB
1110 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
1111 message.workerId
aad6fb64 1112 )
aa9eede8 1113 const workerUsage = this.workerNodes[localWorkerNodeKey].usage
81c02522 1114 // Kill message received from worker
930dcf12
JB
1115 if (
1116 isKillBehavior(KillBehaviors.HARD, message.kill) ||
1e3214b6 1117 (isKillBehavior(KillBehaviors.SOFT, message.kill) &&
7b56f532 1118 ((this.opts.enableTasksQueue === false &&
aa9eede8 1119 workerUsage.tasks.executing === 0) ||
7b56f532 1120 (this.opts.enableTasksQueue === true &&
aa9eede8
JB
1121 workerUsage.tasks.executing === 0 &&
1122 this.tasksQueueSize(localWorkerNodeKey) === 0)))
930dcf12 1123 ) {
041dc05b 1124 this.destroyWorkerNode(localWorkerNodeKey).catch(error => {
5270d253
JB
1125 this.emitter?.emit(PoolEvents.error, error)
1126 })
930dcf12
JB
1127 }
1128 })
46b0bb09 1129 const workerInfo = this.getWorkerInfo(workerNodeKey)
aa9eede8 1130 this.sendToWorker(workerNodeKey, {
b0a4db63 1131 checkActive: true,
21f710aa
JB
1132 workerId: workerInfo.id as number
1133 })
b5e113f6 1134 workerInfo.dynamic = true
b1aae695
JB
1135 if (
1136 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerReady ||
1137 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
1138 ) {
b5e113f6
JB
1139 workerInfo.ready = true
1140 }
33e6bb4c 1141 this.checkAndEmitDynamicWorkerCreationEvents()
aa9eede8 1142 return workerNodeKey
930dcf12
JB
1143 }
1144
a2ed5053 1145 /**
aa9eede8 1146 * Registers a listener callback on the worker given its worker node key.
a2ed5053 1147 *
aa9eede8 1148 * @param workerNodeKey - The worker node key.
a2ed5053
JB
1149 * @param listener - The message listener callback.
1150 */
85aeb3f3
JB
1151 protected abstract registerWorkerMessageListener<
1152 Message extends Data | Response
aa9eede8
JB
1153 >(
1154 workerNodeKey: number,
1155 listener: (message: MessageValue<Message>) => void
1156 ): void
a2ed5053
JB
1157
1158 /**
aa9eede8 1159 * Method hooked up after a worker node has been newly created.
a2ed5053
JB
1160 * Can be overridden.
1161 *
aa9eede8 1162 * @param workerNodeKey - The newly created worker node key.
a2ed5053 1163 */
aa9eede8 1164 protected afterWorkerNodeSetup (workerNodeKey: number): void {
a2ed5053 1165 // Listen to worker messages.
aa9eede8 1166 this.registerWorkerMessageListener(workerNodeKey, this.workerListener())
85aeb3f3 1167 // Send the startup message to worker.
aa9eede8 1168 this.sendStartupMessageToWorker(workerNodeKey)
9edb9717
JB
1169 // Send the statistics message to worker.
1170 this.sendStatisticsMessageToWorker(workerNodeKey)
72695f86 1171 if (this.opts.enableTasksQueue === true) {
dbd73092 1172 if (this.opts.tasksQueueOptions?.taskStealing === true) {
47352846
JB
1173 this.workerNodes[workerNodeKey].onEmptyQueue =
1174 this.taskStealingOnEmptyQueue.bind(this)
1175 }
1176 if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) {
1177 this.workerNodes[workerNodeKey].onBackPressure =
1178 this.tasksStealingOnBackPressure.bind(this)
1179 }
72695f86 1180 }
d2c73f82
JB
1181 }
1182
85aeb3f3 1183 /**
aa9eede8
JB
1184 * Sends the startup message to worker given its worker node key.
1185 *
1186 * @param workerNodeKey - The worker node key.
1187 */
1188 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
1189
1190 /**
9edb9717 1191 * Sends the statistics message to worker given its worker node key.
85aeb3f3 1192 *
aa9eede8 1193 * @param workerNodeKey - The worker node key.
85aeb3f3 1194 */
9edb9717 1195 private sendStatisticsMessageToWorker (workerNodeKey: number): void {
aa9eede8
JB
1196 this.sendToWorker(workerNodeKey, {
1197 statistics: {
1198 runTime:
1199 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1200 .runTime.aggregate,
1201 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1202 .elu.aggregate
1203 },
46b0bb09 1204 workerId: this.getWorkerInfo(workerNodeKey).id as number
aa9eede8
JB
1205 })
1206 }
a2ed5053
JB
1207
1208 private redistributeQueuedTasks (workerNodeKey: number): void {
1209 while (this.tasksQueueSize(workerNodeKey) > 0) {
f201a0cd
JB
1210 const destinationWorkerNodeKey = this.workerNodes.reduce(
1211 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
852ed3e4
JB
1212 return workerNode.info.ready &&
1213 workerNode.usage.tasks.queued <
1214 workerNodes[minWorkerNodeKey].usage.tasks.queued
f201a0cd
JB
1215 ? workerNodeKey
1216 : minWorkerNodeKey
1217 },
1218 0
1219 )
3f690f25
JB
1220 const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
1221 const task = {
1222 ...(this.dequeueTask(workerNodeKey) as Task<Data>),
1223 workerId: destinationWorkerNode.info.id as number
1224 }
1225 if (this.shallExecuteTask(destinationWorkerNodeKey)) {
1226 this.executeTask(destinationWorkerNodeKey, task)
1227 } else {
1228 this.enqueueTask(destinationWorkerNodeKey, task)
dd951876
JB
1229 }
1230 }
1231 }
1232
b1838604
JB
1233 private updateTaskStolenStatisticsWorkerUsage (
1234 workerNodeKey: number,
b1838604
JB
1235 taskName: string
1236 ): void {
1a880eca 1237 const workerNode = this.workerNodes[workerNodeKey]
b1838604
JB
1238 if (workerNode?.usage != null) {
1239 ++workerNode.usage.tasks.stolen
1240 }
1241 if (
1242 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1243 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1244 ) {
1245 const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
1246 taskName
1247 ) as WorkerUsage
1248 ++taskFunctionWorkerUsage.tasks.stolen
1249 }
1250 }
1251
dd951876 1252 private taskStealingOnEmptyQueue (workerId: number): void {
a6b3272b
JB
1253 const destinationWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
1254 const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
dd951876 1255 const workerNodes = this.workerNodes
a6b3272b 1256 .slice()
dd951876
JB
1257 .sort(
1258 (workerNodeA, workerNodeB) =>
1259 workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
1260 )
f201a0cd 1261 const sourceWorkerNode = workerNodes.find(
041dc05b 1262 workerNode =>
f201a0cd
JB
1263 workerNode.info.ready &&
1264 workerNode.info.id !== workerId &&
1265 workerNode.usage.tasks.queued > 0
1266 )
1267 if (sourceWorkerNode != null) {
1268 const task = {
1269 ...(sourceWorkerNode.popTask() as Task<Data>),
1270 workerId: destinationWorkerNode.info.id as number
0bc68267 1271 }
f201a0cd
JB
1272 if (this.shallExecuteTask(destinationWorkerNodeKey)) {
1273 this.executeTask(destinationWorkerNodeKey, task)
1274 } else {
1275 this.enqueueTask(destinationWorkerNodeKey, task)
72695f86 1276 }
f201a0cd
JB
1277 this.updateTaskStolenStatisticsWorkerUsage(
1278 destinationWorkerNodeKey,
1279 task.name as string
1280 )
72695f86
JB
1281 }
1282 }
1283
1284 private tasksStealingOnBackPressure (workerId: number): void {
f778c355
JB
1285 const sizeOffset = 1
1286 if ((this.opts.tasksQueueOptions?.size as number) <= sizeOffset) {
68dbcdc0
JB
1287 return
1288 }
72695f86
JB
1289 const sourceWorkerNode =
1290 this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
1291 const workerNodes = this.workerNodes
a6b3272b 1292 .slice()
72695f86
JB
1293 .sort(
1294 (workerNodeA, workerNodeB) =>
1295 workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
1296 )
1297 for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
1298 if (
0bc68267 1299 sourceWorkerNode.usage.tasks.queued > 0 &&
a6b3272b
JB
1300 workerNode.info.ready &&
1301 workerNode.info.id !== workerId &&
0bc68267 1302 workerNode.usage.tasks.queued <
f778c355 1303 (this.opts.tasksQueueOptions?.size as number) - sizeOffset
72695f86 1304 ) {
dd951876
JB
1305 const task = {
1306 ...(sourceWorkerNode.popTask() as Task<Data>),
1307 workerId: workerNode.info.id as number
1308 }
375f7504 1309 if (this.shallExecuteTask(workerNodeKey)) {
dd951876 1310 this.executeTask(workerNodeKey, task)
4de3d785 1311 } else {
dd951876 1312 this.enqueueTask(workerNodeKey, task)
4de3d785 1313 }
b1838604
JB
1314 this.updateTaskStolenStatisticsWorkerUsage(
1315 workerNodeKey,
b1838604
JB
1316 task.name as string
1317 )
10ecf8fd 1318 }
a2ed5053
JB
1319 }
1320 }
1321
be0676b3 1322 /**
aa9eede8 1323 * This method is the listener registered for each worker message.
be0676b3 1324 *
bdacc2d2 1325 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
1326 */
1327 protected workerListener (): (message: MessageValue<Response>) => void {
041dc05b 1328 return message => {
21f710aa 1329 this.checkMessageWorkerId(message)
a5d15204 1330 if (message.ready != null && message.taskFunctions != null) {
81c02522 1331 // Worker ready response received from worker
10e2aa7e 1332 this.handleWorkerReadyResponse(message)
7629bdf1 1333 } else if (message.taskId != null) {
81c02522 1334 // Task execution response received from worker
6b272951 1335 this.handleTaskExecutionResponse(message)
90d7d101
JB
1336 } else if (message.taskFunctions != null) {
1337 // Task functions message received from worker
46b0bb09
JB
1338 this.getWorkerInfo(
1339 this.getWorkerNodeKeyByWorkerId(message.workerId)
b558f6b5 1340 ).taskFunctions = message.taskFunctions
6b272951
JB
1341 }
1342 }
1343 }
1344
10e2aa7e 1345 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
f05ed93c
JB
1346 if (message.ready === false) {
1347 throw new Error(`Worker ${message.workerId} failed to initialize`)
1348 }
a5d15204 1349 const workerInfo = this.getWorkerInfo(
aad6fb64 1350 this.getWorkerNodeKeyByWorkerId(message.workerId)
46b0bb09 1351 )
a5d15204
JB
1352 workerInfo.ready = message.ready as boolean
1353 workerInfo.taskFunctions = message.taskFunctions
2431bdb4
JB
1354 if (this.emitter != null && this.ready) {
1355 this.emitter.emit(PoolEvents.ready, this.info)
1356 }
6b272951
JB
1357 }
1358
1359 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
5441aea6
JB
1360 const { taskId, taskError, data } = message
1361 const promiseResponse = this.promiseResponseMap.get(taskId as string)
6b272951 1362 if (promiseResponse != null) {
5441aea6
JB
1363 if (taskError != null) {
1364 this.emitter?.emit(PoolEvents.taskError, taskError)
1365 promiseResponse.reject(taskError.message)
6b272951 1366 } else {
5441aea6 1367 promiseResponse.resolve(data as Response)
6b272951 1368 }
501aea93
JB
1369 const workerNodeKey = promiseResponse.workerNodeKey
1370 this.afterTaskExecutionHook(workerNodeKey, message)
f3a91bac 1371 this.workerChoiceStrategyContext.update(workerNodeKey)
5441aea6 1372 this.promiseResponseMap.delete(taskId as string)
6b272951
JB
1373 if (
1374 this.opts.enableTasksQueue === true &&
b5e113f6
JB
1375 this.tasksQueueSize(workerNodeKey) > 0 &&
1376 this.workerNodes[workerNodeKey].usage.tasks.executing <
1377 (this.opts.tasksQueueOptions?.concurrency as number)
6b272951
JB
1378 ) {
1379 this.executeTask(
1380 workerNodeKey,
1381 this.dequeueTask(workerNodeKey) as Task<Data>
1382 )
be0676b3
APA
1383 }
1384 }
be0676b3 1385 }
7c0ba920 1386
a1763c54 1387 private checkAndEmitTaskExecutionEvents (): void {
33e6bb4c
JB
1388 if (this.busy) {
1389 this.emitter?.emit(PoolEvents.busy, this.info)
a1763c54
JB
1390 }
1391 }
1392
1393 private checkAndEmitTaskQueuingEvents (): void {
1394 if (this.hasBackPressure()) {
1395 this.emitter?.emit(PoolEvents.backPressure, this.info)
164d950a
JB
1396 }
1397 }
1398
33e6bb4c
JB
1399 private checkAndEmitDynamicWorkerCreationEvents (): void {
1400 if (this.type === PoolTypes.dynamic) {
1401 if (this.full) {
1402 this.emitter?.emit(PoolEvents.full, this.info)
1403 }
1404 }
1405 }
1406
8a1260a3 1407 /**
aa9eede8 1408 * Gets the worker information given its worker node key.
8a1260a3
JB
1409 *
1410 * @param workerNodeKey - The worker node key.
3f09ed9f 1411 * @returns The worker information.
8a1260a3 1412 */
46b0bb09
JB
1413 protected getWorkerInfo (workerNodeKey: number): WorkerInfo {
1414 return this.workerNodes[workerNodeKey].info
e221309a
JB
1415 }
1416
a05c10de 1417 /**
b0a4db63 1418 * Adds the given worker in the pool worker nodes.
ea7a90d3 1419 *
38e795c1 1420 * @param worker - The worker.
aa9eede8
JB
1421 * @returns The added worker node key.
1422 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
ea7a90d3 1423 */
b0a4db63 1424 private addWorkerNode (worker: Worker): number {
671d5154
JB
1425 const workerNode = new WorkerNode<Worker, Data>(
1426 worker,
ff3f866a 1427 this.opts.tasksQueueOptions?.size ?? Math.pow(this.maxSize, 2)
671d5154 1428 )
b97d82d8 1429 // Flag the worker node as ready at pool startup.
d2c73f82
JB
1430 if (this.starting) {
1431 workerNode.info.ready = true
1432 }
aa9eede8 1433 this.workerNodes.push(workerNode)
aad6fb64 1434 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
aa9eede8 1435 if (workerNodeKey === -1) {
86ed0598 1436 throw new Error('Worker added not found in worker nodes')
aa9eede8
JB
1437 }
1438 return workerNodeKey
ea7a90d3 1439 }
c923ce56 1440
51fe3d3c 1441 /**
f06e48d8 1442 * Removes the given worker from the pool worker nodes.
51fe3d3c 1443 *
f06e48d8 1444 * @param worker - The worker.
51fe3d3c 1445 */
416fd65c 1446 private removeWorkerNode (worker: Worker): void {
aad6fb64 1447 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1f68cede
JB
1448 if (workerNodeKey !== -1) {
1449 this.workerNodes.splice(workerNodeKey, 1)
1450 this.workerChoiceStrategyContext.remove(workerNodeKey)
1451 }
51fe3d3c 1452 }
adc3c320 1453
e2b31e32
JB
1454 /** @inheritDoc */
1455 public hasWorkerNodeBackPressure (workerNodeKey: number): boolean {
9e844245 1456 return (
e2b31e32
JB
1457 this.opts.enableTasksQueue === true &&
1458 this.workerNodes[workerNodeKey].hasBackPressure()
9e844245
JB
1459 )
1460 }
1461
1462 private hasBackPressure (): boolean {
1463 return (
1464 this.opts.enableTasksQueue === true &&
1465 this.workerNodes.findIndex(
041dc05b 1466 workerNode => !workerNode.hasBackPressure()
a1763c54 1467 ) === -1
9e844245 1468 )
e2b31e32
JB
1469 }
1470
b0a4db63 1471 /**
aa9eede8 1472 * Executes the given task on the worker given its worker node key.
b0a4db63 1473 *
aa9eede8 1474 * @param workerNodeKey - The worker node key.
b0a4db63
JB
1475 * @param task - The task to execute.
1476 */
2e81254d 1477 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1c6fe997 1478 this.beforeTaskExecutionHook(workerNodeKey, task)
bbfa38a2 1479 this.sendToWorker(workerNodeKey, task, task.transferList)
a1763c54 1480 this.checkAndEmitTaskExecutionEvents()
2e81254d
JB
1481 }
1482
f9f00b5f 1483 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
a1763c54
JB
1484 const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
1485 this.checkAndEmitTaskQueuingEvents()
1486 return tasksQueueSize
adc3c320
JB
1487 }
1488
416fd65c 1489 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
4b628b48 1490 return this.workerNodes[workerNodeKey].dequeueTask()
adc3c320
JB
1491 }
1492
416fd65c 1493 private tasksQueueSize (workerNodeKey: number): number {
4b628b48 1494 return this.workerNodes[workerNodeKey].tasksQueueSize()
df593701
JB
1495 }
1496
81c02522 1497 protected flushTasksQueue (workerNodeKey: number): void {
920278a2
JB
1498 while (this.tasksQueueSize(workerNodeKey) > 0) {
1499 this.executeTask(
1500 workerNodeKey,
1501 this.dequeueTask(workerNodeKey) as Task<Data>
1502 )
ff733df7 1503 }
4b628b48 1504 this.workerNodes[workerNodeKey].clearTasksQueue()
ff733df7
JB
1505 }
1506
ef41a6e6
JB
1507 private flushTasksQueues (): void {
1508 for (const [workerNodeKey] of this.workerNodes.entries()) {
1509 this.flushTasksQueue(workerNodeKey)
1510 }
1511 }
c97c7edb 1512}