docs: update benchmark vs. external pools
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
62c15a68 2import { performance } from 'node:perf_hooks'
2740a743 3import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
bbeadd16
JB
4import {
5 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
6 EMPTY_FUNCTION,
0d80593b 7 isPlainObject,
bbeadd16
JB
8 median
9} from '../utils'
34a0cfab 10import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
65d7a1c9 11import { CircularArray } from '../circular-array'
29ee7e9a 12import { Queue } from '../queue'
c4855468 13import {
65d7a1c9 14 type IPool,
7c5a1080 15 PoolEmitter,
c4855468 16 PoolEvents,
6b27d407 17 type PoolInfo,
c4855468 18 type PoolOptions,
6b27d407
JB
19 type PoolType,
20 PoolTypes,
184855e6
JB
21 type TasksQueueOptions,
22 type WorkerType
c4855468 23} from './pool'
8604aaab
JB
24import type {
25 IWorker,
26 Task,
27 TaskStatistics,
28 WorkerNode,
29 WorkerUsage
30} from './worker'
a35560ba
S
31import {
32 WorkerChoiceStrategies,
a20f0ba5
JB
33 type WorkerChoiceStrategy,
34 type WorkerChoiceStrategyOptions
bdaf31cd
JB
35} from './selection-strategies/selection-strategies-types'
36import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 37
729c563d 38/**
ea7a90d3 39 * Base class that implements some shared logic for all poolifier pools.
729c563d 40 *
38e795c1
JB
41 * @typeParam Worker - Type of worker which manages this pool.
42 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 43 * @typeParam Response - Type of execution response. This can only be serializable data.
729c563d 44 */
c97c7edb 45export abstract class AbstractPool<
f06e48d8 46 Worker extends IWorker,
d3c8a1a8
S
47 Data = unknown,
48 Response = unknown
c4855468 49> implements IPool<Worker, Data, Response> {
afc003b2 50 /** @inheritDoc */
f06e48d8 51 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
4a6952ff 52
afc003b2 53 /** @inheritDoc */
7c0ba920
JB
54 public readonly emitter?: PoolEmitter
55
be0676b3 56 /**
a3445496 57 * The execution response promise map.
be0676b3 58 *
2740a743 59 * - `key`: The message id of each submitted task.
a3445496 60 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
be0676b3 61 *
a3445496 62 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 63 */
c923ce56
JB
64 protected promiseResponseMap: Map<
65 string,
66 PromiseResponseWrapper<Worker, Response>
67 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
c97c7edb 68
a35560ba 69 /**
51fe3d3c 70 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba
S
71 */
72 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
73 Worker,
74 Data,
75 Response
a35560ba
S
76 >
77
729c563d
S
78 /**
79 * Constructs a new poolifier pool.
80 *
38e795c1 81 * @param numberOfWorkers - Number of workers that this pool should manage.
029715f0 82 * @param filePath - Path to the worker file.
38e795c1 83 * @param opts - Options for the pool.
729c563d 84 */
c97c7edb 85 public constructor (
b4213b7f
JB
86 protected readonly numberOfWorkers: number,
87 protected readonly filePath: string,
88 protected readonly opts: PoolOptions<Worker>
c97c7edb 89 ) {
78cea37e 90 if (!this.isMain()) {
c97c7edb
S
91 throw new Error('Cannot start a pool from a worker!')
92 }
8d3782fa 93 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 94 this.checkFilePath(this.filePath)
7c0ba920 95 this.checkPoolOptions(this.opts)
1086026a 96
7254e419
JB
97 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
98 this.executeTask = this.executeTask.bind(this)
99 this.enqueueTask = this.enqueueTask.bind(this)
100 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
1086026a 101
6bd72cd0 102 if (this.opts.enableEvents === true) {
7c0ba920
JB
103 this.emitter = new PoolEmitter()
104 }
d59df138
JB
105 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
106 Worker,
107 Data,
108 Response
da309861
JB
109 >(
110 this,
111 this.opts.workerChoiceStrategy,
112 this.opts.workerChoiceStrategyOptions
113 )
b6b32453
JB
114
115 this.setupHook()
116
117 for (let i = 1; i <= this.numberOfWorkers; i++) {
118 this.createAndSetupWorker()
119 }
c97c7edb
S
120 }
121
a35560ba 122 private checkFilePath (filePath: string): void {
ffcbbad8
JB
123 if (
124 filePath == null ||
125 (typeof filePath === 'string' && filePath.trim().length === 0)
126 ) {
c510fea7
APA
127 throw new Error('Please specify a file with a worker implementation')
128 }
129 }
130
8d3782fa
JB
131 private checkNumberOfWorkers (numberOfWorkers: number): void {
132 if (numberOfWorkers == null) {
133 throw new Error(
134 'Cannot instantiate a pool without specifying the number of workers'
135 )
78cea37e 136 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 137 throw new TypeError(
0d80593b 138 'Cannot instantiate a pool with a non safe integer number of workers'
8d3782fa
JB
139 )
140 } else if (numberOfWorkers < 0) {
473c717a 141 throw new RangeError(
8d3782fa
JB
142 'Cannot instantiate a pool with a negative number of workers'
143 )
6b27d407 144 } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
8d3782fa
JB
145 throw new Error('Cannot instantiate a fixed pool with no worker')
146 }
147 }
148
7c0ba920 149 private checkPoolOptions (opts: PoolOptions<Worker>): void {
0d80593b
JB
150 if (isPlainObject(opts)) {
151 this.opts.workerChoiceStrategy =
152 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
153 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
154 this.opts.workerChoiceStrategyOptions =
155 opts.workerChoiceStrategyOptions ??
156 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
49be33fe
JB
157 this.checkValidWorkerChoiceStrategyOptions(
158 this.opts.workerChoiceStrategyOptions
159 )
1f68cede 160 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
0d80593b
JB
161 this.opts.enableEvents = opts.enableEvents ?? true
162 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
163 if (this.opts.enableTasksQueue) {
164 this.checkValidTasksQueueOptions(
165 opts.tasksQueueOptions as TasksQueueOptions
166 )
167 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
168 opts.tasksQueueOptions as TasksQueueOptions
169 )
170 }
171 } else {
172 throw new TypeError('Invalid pool options: must be a plain object')
7171d33f 173 }
aee46736
JB
174 }
175
176 private checkValidWorkerChoiceStrategy (
177 workerChoiceStrategy: WorkerChoiceStrategy
178 ): void {
179 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
b529c323 180 throw new Error(
aee46736 181 `Invalid worker choice strategy '${workerChoiceStrategy}'`
b529c323
JB
182 )
183 }
7c0ba920
JB
184 }
185
0d80593b
JB
186 private checkValidWorkerChoiceStrategyOptions (
187 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
188 ): void {
189 if (!isPlainObject(workerChoiceStrategyOptions)) {
190 throw new TypeError(
191 'Invalid worker choice strategy options: must be a plain object'
192 )
193 }
49be33fe
JB
194 if (
195 workerChoiceStrategyOptions.weights != null &&
6b27d407 196 Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
49be33fe
JB
197 ) {
198 throw new Error(
199 'Invalid worker choice strategy options: must have a weight for each worker node'
200 )
201 }
0d80593b
JB
202 }
203
a20f0ba5
JB
204 private checkValidTasksQueueOptions (
205 tasksQueueOptions: TasksQueueOptions
206 ): void {
0d80593b
JB
207 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
208 throw new TypeError('Invalid tasks queue options: must be a plain object')
209 }
a20f0ba5
JB
210 if ((tasksQueueOptions?.concurrency as number) <= 0) {
211 throw new Error(
212 `Invalid worker tasks concurrency '${
213 tasksQueueOptions.concurrency as number
214 }'`
215 )
216 }
217 }
218
08f3f44c 219 /** @inheritDoc */
6b27d407
JB
220 public get info (): PoolInfo {
221 return {
222 type: this.type,
184855e6 223 worker: this.worker,
6b27d407
JB
224 minSize: this.minSize,
225 maxSize: this.maxSize,
226 workerNodes: this.workerNodes.length,
227 idleWorkerNodes: this.workerNodes.reduce(
228 (accumulator, workerNode) =>
a4e07f72
JB
229 workerNode.workerUsage.tasks.executing === 0
230 ? accumulator + 1
231 : accumulator,
6b27d407
JB
232 0
233 ),
234 busyWorkerNodes: this.workerNodes.reduce(
235 (accumulator, workerNode) =>
a4e07f72
JB
236 workerNode.workerUsage.tasks.executing > 0
237 ? accumulator + 1
238 : accumulator,
6b27d407
JB
239 0
240 ),
a4e07f72 241 executedTasks: this.workerNodes.reduce(
6b27d407 242 (accumulator, workerNode) =>
a4e07f72
JB
243 accumulator + workerNode.workerUsage.tasks.executed,
244 0
245 ),
246 executingTasks: this.workerNodes.reduce(
247 (accumulator, workerNode) =>
248 accumulator + workerNode.workerUsage.tasks.executing,
6b27d407
JB
249 0
250 ),
251 queuedTasks: this.workerNodes.reduce(
252 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
253 0
254 ),
255 maxQueuedTasks: this.workerNodes.reduce(
256 (accumulator, workerNode) =>
257 accumulator + workerNode.tasksQueue.maxSize,
258 0
a4e07f72
JB
259 ),
260 failedTasks: this.workerNodes.reduce(
261 (accumulator, workerNode) =>
262 accumulator + workerNode.workerUsage.tasks.failed,
263 0
6b27d407
JB
264 )
265 }
266 }
08f3f44c 267
8881ae32
JB
268 /**
269 * Pool type.
270 *
271 * If it is `'dynamic'`, it provides the `max` property.
272 */
273 protected abstract get type (): PoolType
274
184855e6
JB
275 /**
276 * Gets the worker type.
277 */
278 protected abstract get worker (): WorkerType
279
c2ade475 280 /**
6b27d407 281 * Pool minimum size.
c2ade475 282 */
6b27d407 283 protected abstract get minSize (): number
ff733df7
JB
284
285 /**
6b27d407 286 * Pool maximum size.
ff733df7 287 */
6b27d407 288 protected abstract get maxSize (): number
a35560ba 289
ffcbbad8 290 /**
f06e48d8 291 * Gets the given worker its worker node key.
ffcbbad8
JB
292 *
293 * @param worker - The worker.
f06e48d8 294 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
ffcbbad8 295 */
f06e48d8
JB
296 private getWorkerNodeKey (worker: Worker): number {
297 return this.workerNodes.findIndex(
298 workerNode => workerNode.worker === worker
299 )
bf9549ae
JB
300 }
301
afc003b2 302 /** @inheritDoc */
a35560ba 303 public setWorkerChoiceStrategy (
59219cbb
JB
304 workerChoiceStrategy: WorkerChoiceStrategy,
305 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 306 ): void {
aee46736 307 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
b98ec2e6 308 this.opts.workerChoiceStrategy = workerChoiceStrategy
b6b32453
JB
309 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
310 this.opts.workerChoiceStrategy
311 )
312 if (workerChoiceStrategyOptions != null) {
313 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
314 }
0ebe2a9f 315 for (const workerNode of this.workerNodes) {
8604aaab
JB
316 this.setWorkerNodeTasksUsage(
317 workerNode,
318 this.getWorkerUsage(workerNode.worker)
319 )
b6b32453 320 this.setWorkerStatistics(workerNode.worker)
59219cbb 321 }
a20f0ba5
JB
322 }
323
324 /** @inheritDoc */
325 public setWorkerChoiceStrategyOptions (
326 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
327 ): void {
0d80593b 328 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
a20f0ba5
JB
329 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
330 this.workerChoiceStrategyContext.setOptions(
331 this.opts.workerChoiceStrategyOptions
a35560ba
S
332 )
333 }
334
a20f0ba5 335 /** @inheritDoc */
8f52842f
JB
336 public enableTasksQueue (
337 enable: boolean,
338 tasksQueueOptions?: TasksQueueOptions
339 ): void {
a20f0ba5 340 if (this.opts.enableTasksQueue === true && !enable) {
ef41a6e6 341 this.flushTasksQueues()
a20f0ba5
JB
342 }
343 this.opts.enableTasksQueue = enable
8f52842f 344 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
a20f0ba5
JB
345 }
346
347 /** @inheritDoc */
8f52842f 348 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
a20f0ba5 349 if (this.opts.enableTasksQueue === true) {
8f52842f
JB
350 this.checkValidTasksQueueOptions(tasksQueueOptions)
351 this.opts.tasksQueueOptions =
352 this.buildTasksQueueOptions(tasksQueueOptions)
5baee0d7 353 } else if (this.opts.tasksQueueOptions != null) {
a20f0ba5
JB
354 delete this.opts.tasksQueueOptions
355 }
356 }
357
358 private buildTasksQueueOptions (
359 tasksQueueOptions: TasksQueueOptions
360 ): TasksQueueOptions {
361 return {
362 concurrency: tasksQueueOptions?.concurrency ?? 1
363 }
364 }
365
c319c66b
JB
366 /**
367 * Whether the pool is full or not.
368 *
369 * The pool filling boolean status.
370 */
dea903a8
JB
371 protected get full (): boolean {
372 return this.workerNodes.length >= this.maxSize
373 }
c2ade475 374
c319c66b
JB
375 /**
376 * Whether the pool is busy or not.
377 *
378 * The pool busyness boolean status.
379 */
380 protected abstract get busy (): boolean
7c0ba920 381
6c6afb84
JB
382 /**
383 * Whether worker nodes are executing at least one task.
384 *
385 * @returns Worker nodes busyness boolean status.
386 */
c2ade475 387 protected internalBusy (): boolean {
e0ae6100
JB
388 return (
389 this.workerNodes.findIndex(workerNode => {
a4e07f72 390 return workerNode.workerUsage.tasks.executing === 0
e0ae6100
JB
391 }) === -1
392 )
cb70b19d
JB
393 }
394
afc003b2 395 /** @inheritDoc */
a86b6df1 396 public async execute (data?: Data, name?: string): Promise<Response> {
b6b32453 397 const timestamp = performance.now()
20dcad1a 398 const workerNodeKey = this.chooseWorkerNode()
adc3c320 399 const submittedTask: Task<Data> = {
a86b6df1 400 name,
e5a5c0fc
JB
401 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
402 data: data ?? ({} as Data),
b6b32453 403 timestamp,
adc3c320
JB
404 id: crypto.randomUUID()
405 }
2e81254d 406 const res = new Promise<Response>((resolve, reject) => {
02706357 407 this.promiseResponseMap.set(submittedTask.id as string, {
2e81254d
JB
408 resolve,
409 reject,
20dcad1a 410 worker: this.workerNodes[workerNodeKey].worker
2e81254d
JB
411 })
412 })
ff733df7
JB
413 if (
414 this.opts.enableTasksQueue === true &&
7171d33f 415 (this.busy ||
a4e07f72 416 this.workerNodes[workerNodeKey].workerUsage.tasks.executing >=
7171d33f 417 ((this.opts.tasksQueueOptions as TasksQueueOptions)
3528c992 418 .concurrency as number))
ff733df7 419 ) {
26a929d7
JB
420 this.enqueueTask(workerNodeKey, submittedTask)
421 } else {
2e81254d 422 this.executeTask(workerNodeKey, submittedTask)
adc3c320 423 }
ff733df7 424 this.checkAndEmitEvents()
78cea37e 425 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
426 return res
427 }
c97c7edb 428
afc003b2 429 /** @inheritDoc */
c97c7edb 430 public async destroy (): Promise<void> {
1fbcaa7c 431 await Promise.all(
875a7c37
JB
432 this.workerNodes.map(async (workerNode, workerNodeKey) => {
433 this.flushTasksQueue(workerNodeKey)
47aacbaa 434 // FIXME: wait for tasks to be finished
f06e48d8 435 await this.destroyWorker(workerNode.worker)
1fbcaa7c
JB
436 })
437 )
c97c7edb
S
438 }
439
4a6952ff 440 /**
6c6afb84 441 * Terminates the given worker.
4a6952ff 442 *
f06e48d8 443 * @param worker - A worker within `workerNodes`.
4a6952ff
JB
444 */
445 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 446
729c563d 447 /**
2e81254d 448 * Setup hook to execute code before worker node are created in the abstract constructor.
d99ba5a8 449 * Can be overridden
afc003b2
JB
450 *
451 * @virtual
729c563d 452 */
280c2a77 453 protected setupHook (): void {
d99ba5a8 454 // Intentionally empty
280c2a77 455 }
c97c7edb 456
729c563d 457 /**
280c2a77
S
458 * Should return whether the worker is the main worker or not.
459 */
460 protected abstract isMain (): boolean
461
462 /**
2e81254d 463 * Hook executed before the worker task execution.
bf9549ae 464 * Can be overridden.
729c563d 465 *
f06e48d8 466 * @param workerNodeKey - The worker node key.
1c6fe997 467 * @param task - The task to execute.
729c563d 468 */
1c6fe997
JB
469 protected beforeTaskExecutionHook (
470 workerNodeKey: number,
471 task: Task<Data>
472 ): void {
473 const workerUsage = this.workerNodes[workerNodeKey].workerUsage
474 ++workerUsage.tasks.executing
475 this.updateWaitTimeWorkerUsage(workerUsage, task)
c97c7edb
S
476 }
477
c01733f1 478 /**
2e81254d 479 * Hook executed after the worker task execution.
bf9549ae 480 * Can be overridden.
c01733f1 481 *
c923ce56 482 * @param worker - The worker.
38e795c1 483 * @param message - The received message.
c01733f1 484 */
2e81254d 485 protected afterTaskExecutionHook (
c923ce56 486 worker: Worker,
2740a743 487 message: MessageValue<Response>
bf9549ae 488 ): void {
a4e07f72
JB
489 const workerUsage =
490 this.workerNodes[this.getWorkerNodeKey(worker)].workerUsage
f1c06930
JB
491 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
492 this.updateRunTimeWorkerUsage(workerUsage, message)
493 this.updateEluWorkerUsage(workerUsage, message)
494 }
495
496 private updateTaskStatisticsWorkerUsage (
497 workerUsage: WorkerUsage,
498 message: MessageValue<Response>
499 ): void {
a4e07f72
JB
500 const workerTaskStatistics = workerUsage.tasks
501 --workerTaskStatistics.executing
502 ++workerTaskStatistics.executed
82f36766 503 if (message.taskError != null) {
a4e07f72 504 ++workerTaskStatistics.failed
2740a743 505 }
f8eb0a2a
JB
506 }
507
a4e07f72
JB
508 private updateRunTimeWorkerUsage (
509 workerUsage: WorkerUsage,
f8eb0a2a
JB
510 message: MessageValue<Response>
511 ): void {
87de9ff5
JB
512 if (
513 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
932fc8be 514 .aggregate
87de9ff5 515 ) {
932fc8be 516 workerUsage.runTime.aggregate += message.taskPerformance?.runTime ?? 0
c6bd2650 517 if (
932fc8be
JB
518 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
519 .average &&
a4e07f72 520 workerUsage.tasks.executed !== 0
c6bd2650 521 ) {
a4e07f72 522 workerUsage.runTime.average =
f1c06930
JB
523 workerUsage.runTime.aggregate /
524 (workerUsage.tasks.executed - workerUsage.tasks.failed)
3032893a 525 }
3fa4cdd2 526 if (
932fc8be
JB
527 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
528 .median &&
d715b7bc 529 message.taskPerformance?.runTime != null
3fa4cdd2 530 ) {
a4e07f72
JB
531 workerUsage.runTime.history.push(message.taskPerformance.runTime)
532 workerUsage.runTime.median = median(workerUsage.runTime.history)
78099a15 533 }
3032893a 534 }
f8eb0a2a
JB
535 }
536
a4e07f72
JB
537 private updateWaitTimeWorkerUsage (
538 workerUsage: WorkerUsage,
1c6fe997 539 task: Task<Data>
f8eb0a2a 540 ): void {
1c6fe997
JB
541 const timestamp = performance.now()
542 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
87de9ff5
JB
543 if (
544 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime
932fc8be 545 .aggregate
87de9ff5 546 ) {
932fc8be 547 workerUsage.waitTime.aggregate += taskWaitTime ?? 0
09a6305f 548 if (
87de9ff5 549 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 550 .waitTime.average &&
a4e07f72 551 workerUsage.tasks.executed !== 0
09a6305f 552 ) {
a4e07f72 553 workerUsage.waitTime.average =
f1c06930
JB
554 workerUsage.waitTime.aggregate /
555 (workerUsage.tasks.executed - workerUsage.tasks.failed)
09a6305f
JB
556 }
557 if (
87de9ff5 558 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 559 .waitTime.median &&
1c6fe997 560 taskWaitTime != null
09a6305f 561 ) {
1c6fe997 562 workerUsage.waitTime.history.push(taskWaitTime)
a4e07f72 563 workerUsage.waitTime.median = median(workerUsage.waitTime.history)
09a6305f 564 }
0567595a 565 }
c01733f1 566 }
567
a4e07f72 568 private updateEluWorkerUsage (
5df69fab 569 workerUsage: WorkerUsage,
62c15a68
JB
570 message: MessageValue<Response>
571 ): void {
5df69fab
JB
572 if (
573 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
574 .aggregate
575 ) {
576 if (workerUsage.elu != null && message.taskPerformance?.elu != null) {
9adcefab
JB
577 workerUsage.elu.idle.aggregate += message.taskPerformance.elu.idle
578 workerUsage.elu.active.aggregate += message.taskPerformance.elu.active
5df69fab
JB
579 workerUsage.elu.utilization =
580 (workerUsage.elu.utilization +
581 message.taskPerformance.elu.utilization) /
582 2
583 } else if (message.taskPerformance?.elu != null) {
584 workerUsage.elu.idle.aggregate = message.taskPerformance.elu.idle
585 workerUsage.elu.active.aggregate = message.taskPerformance.elu.active
586 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
587 }
d715b7bc 588 if (
5df69fab
JB
589 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
590 .average &&
591 workerUsage.tasks.executed !== 0
592 ) {
f1c06930
JB
593 const executedTasks =
594 workerUsage.tasks.executed - workerUsage.tasks.failed
5df69fab 595 workerUsage.elu.idle.average =
f1c06930 596 workerUsage.elu.idle.aggregate / executedTasks
5df69fab 597 workerUsage.elu.active.average =
f1c06930 598 workerUsage.elu.active.aggregate / executedTasks
5df69fab
JB
599 }
600 if (
601 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
602 .median &&
d715b7bc
JB
603 message.taskPerformance?.elu != null
604 ) {
5df69fab
JB
605 workerUsage.elu.idle.history.push(message.taskPerformance.elu.idle)
606 workerUsage.elu.active.history.push(message.taskPerformance.elu.active)
607 workerUsage.elu.idle.median = median(workerUsage.elu.idle.history)
608 workerUsage.elu.active.median = median(workerUsage.elu.active.history)
62c15a68
JB
609 }
610 }
611 }
612
280c2a77 613 /**
f06e48d8 614 * Chooses a worker node for the next task.
280c2a77 615 *
6c6afb84 616 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
280c2a77 617 *
20dcad1a 618 * @returns The worker node key
280c2a77 619 */
6c6afb84 620 private chooseWorkerNode (): number {
930dcf12 621 if (this.shallCreateDynamicWorker()) {
6c6afb84
JB
622 const worker = this.createAndSetupDynamicWorker()
623 if (
624 this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker
625 ) {
626 return this.getWorkerNodeKey(worker)
627 }
17393ac8 628 }
930dcf12
JB
629 return this.workerChoiceStrategyContext.execute()
630 }
631
6c6afb84
JB
632 /**
633 * Conditions for dynamic worker creation.
634 *
635 * @returns Whether to create a dynamic worker or not.
636 */
637 private shallCreateDynamicWorker (): boolean {
930dcf12 638 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
c97c7edb
S
639 }
640
280c2a77 641 /**
675bb809 642 * Sends a message to the given worker.
280c2a77 643 *
38e795c1
JB
644 * @param worker - The worker which should receive the message.
645 * @param message - The message.
280c2a77
S
646 */
647 protected abstract sendToWorker (
648 worker: Worker,
649 message: MessageValue<Data>
650 ): void
651
4a6952ff 652 /**
f06e48d8 653 * Registers a listener callback on the given worker.
4a6952ff 654 *
38e795c1
JB
655 * @param worker - The worker which should register a listener.
656 * @param listener - The message listener callback.
4a6952ff
JB
657 */
658 protected abstract registerWorkerMessageListener<
4f7fa42a 659 Message extends Data | Response
78cea37e 660 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 661
729c563d 662 /**
41344292 663 * Creates a new worker.
6c6afb84
JB
664 *
665 * @returns Newly created worker.
729c563d 666 */
280c2a77 667 protected abstract createWorker (): Worker
c97c7edb 668
729c563d 669 /**
f06e48d8 670 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
729c563d 671 *
38e795c1 672 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 673 *
38e795c1 674 * @param worker - The newly created worker.
729c563d 675 */
280c2a77 676 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 677
4a6952ff 678 /**
f06e48d8 679 * Creates a new worker and sets it up completely in the pool worker nodes.
4a6952ff
JB
680 *
681 * @returns New, completely set up worker.
682 */
683 protected createAndSetupWorker (): Worker {
bdacc2d2 684 const worker = this.createWorker()
280c2a77 685
35cf1c03 686 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba 687 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
1f68cede
JB
688 worker.on('error', error => {
689 if (this.emitter != null) {
690 this.emitter.emit(PoolEvents.error, error)
691 }
5baee0d7 692 if (this.opts.restartWorkerOnError === true) {
1f68cede 693 this.createAndSetupWorker()
5baee0d7
JB
694 }
695 })
a35560ba
S
696 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
697 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 698 worker.once('exit', () => {
f06e48d8 699 this.removeWorkerNode(worker)
a974afa6 700 })
280c2a77 701
f06e48d8 702 this.pushWorkerNode(worker)
280c2a77 703
b6b32453
JB
704 this.setWorkerStatistics(worker)
705
280c2a77
S
706 this.afterWorkerSetup(worker)
707
c97c7edb
S
708 return worker
709 }
be0676b3 710
930dcf12
JB
711 /**
712 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
713 *
714 * @returns New, completely set up dynamic worker.
715 */
716 protected createAndSetupDynamicWorker (): Worker {
717 const worker = this.createAndSetupWorker()
718 this.registerWorkerMessageListener(worker, message => {
e8b3a5ab 719 const workerNodeKey = this.getWorkerNodeKey(worker)
930dcf12
JB
720 if (
721 isKillBehavior(KillBehaviors.HARD, message.kill) ||
7b56f532
JB
722 (message.kill != null &&
723 ((this.opts.enableTasksQueue === false &&
e8b3a5ab
JB
724 this.workerNodes[workerNodeKey].workerUsage.tasks.executing ===
725 0) ||
7b56f532 726 (this.opts.enableTasksQueue === true &&
e8b3a5ab
JB
727 this.workerNodes[workerNodeKey].workerUsage.tasks.executing ===
728 0 &&
729 this.tasksQueueSize(workerNodeKey) === 0)))
930dcf12
JB
730 ) {
731 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
930dcf12
JB
732 void (this.destroyWorker(worker) as Promise<void>)
733 }
734 })
735 return worker
736 }
737
be0676b3 738 /**
ff733df7 739 * This function is the listener registered for each worker message.
be0676b3 740 *
bdacc2d2 741 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
742 */
743 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 744 return message => {
b1989cfd 745 if (message.id != null) {
a3445496 746 // Task execution response received
2740a743 747 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 748 if (promiseResponse != null) {
82f36766
JB
749 if (message.taskError != null) {
750 promiseResponse.reject(message.taskError.message)
91ee39ed 751 if (this.emitter != null) {
82f36766 752 this.emitter.emit(PoolEvents.taskError, message.taskError)
91ee39ed 753 }
a05c10de 754 } else {
2740a743 755 promiseResponse.resolve(message.data as Response)
a05c10de 756 }
2e81254d 757 this.afterTaskExecutionHook(promiseResponse.worker, message)
2740a743 758 this.promiseResponseMap.delete(message.id)
ff733df7
JB
759 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
760 if (
761 this.opts.enableTasksQueue === true &&
416fd65c 762 this.tasksQueueSize(workerNodeKey) > 0
ff733df7 763 ) {
2e81254d
JB
764 this.executeTask(
765 workerNodeKey,
ff733df7
JB
766 this.dequeueTask(workerNodeKey) as Task<Data>
767 )
768 }
e5536a06 769 this.workerChoiceStrategyContext.update(workerNodeKey)
be0676b3
APA
770 }
771 }
772 }
be0676b3 773 }
7c0ba920 774
ff733df7 775 private checkAndEmitEvents (): void {
1f68cede 776 if (this.emitter != null) {
ff733df7 777 if (this.busy) {
6b27d407 778 this.emitter?.emit(PoolEvents.busy, this.info)
ff733df7 779 }
6b27d407
JB
780 if (this.type === PoolTypes.dynamic && this.full) {
781 this.emitter?.emit(PoolEvents.full, this.info)
ff733df7 782 }
164d950a
JB
783 }
784 }
785
0ebe2a9f
JB
786 /**
787 * Sets the given worker node its tasks usage in the pool.
788 *
789 * @param workerNode - The worker node.
a4e07f72 790 * @param workerUsage - The worker usage.
0ebe2a9f
JB
791 */
792 private setWorkerNodeTasksUsage (
793 workerNode: WorkerNode<Worker, Data>,
a4e07f72 794 workerUsage: WorkerUsage
0ebe2a9f 795 ): void {
a4e07f72 796 workerNode.workerUsage = workerUsage
0ebe2a9f
JB
797 }
798
a05c10de 799 /**
f06e48d8 800 * Pushes the given worker in the pool worker nodes.
ea7a90d3 801 *
38e795c1 802 * @param worker - The worker.
f06e48d8 803 * @returns The worker nodes length.
ea7a90d3 804 */
f06e48d8
JB
805 private pushWorkerNode (worker: Worker): number {
806 return this.workerNodes.push({
ffcbbad8 807 worker,
8604aaab 808 workerUsage: this.getWorkerUsage(worker),
29ee7e9a 809 tasksQueue: new Queue<Task<Data>>()
ea7a90d3
JB
810 })
811 }
c923ce56 812
8604aaab
JB
813 // /**
814 // * Sets the given worker in the pool worker nodes.
815 // *
816 // * @param workerNodeKey - The worker node key.
817 // * @param worker - The worker.
818 // * @param workerUsage - The worker usage.
819 // * @param tasksQueue - The worker task queue.
820 // */
821 // private setWorkerNode (
822 // workerNodeKey: number,
823 // worker: Worker,
824 // workerUsage: WorkerUsage,
825 // tasksQueue: Queue<Task<Data>>
826 // ): void {
827 // this.workerNodes[workerNodeKey] = {
828 // worker,
829 // workerUsage,
830 // tasksQueue
831 // }
832 // }
51fe3d3c
JB
833
834 /**
f06e48d8 835 * Removes the given worker from the pool worker nodes.
51fe3d3c 836 *
f06e48d8 837 * @param worker - The worker.
51fe3d3c 838 */
416fd65c 839 private removeWorkerNode (worker: Worker): void {
f06e48d8 840 const workerNodeKey = this.getWorkerNodeKey(worker)
1f68cede
JB
841 if (workerNodeKey !== -1) {
842 this.workerNodes.splice(workerNodeKey, 1)
843 this.workerChoiceStrategyContext.remove(workerNodeKey)
844 }
51fe3d3c 845 }
adc3c320 846
2e81254d 847 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1c6fe997 848 this.beforeTaskExecutionHook(workerNodeKey, task)
2e81254d
JB
849 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
850 }
851
f9f00b5f 852 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
29ee7e9a 853 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
adc3c320
JB
854 }
855
416fd65c 856 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
29ee7e9a 857 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
adc3c320
JB
858 }
859
416fd65c 860 private tasksQueueSize (workerNodeKey: number): number {
4d8bf9e4 861 return this.workerNodes[workerNodeKey].tasksQueue.size
adc3c320 862 }
ff733df7 863
416fd65c
JB
864 private flushTasksQueue (workerNodeKey: number): void {
865 if (this.tasksQueueSize(workerNodeKey) > 0) {
29ee7e9a
JB
866 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
867 this.executeTask(
868 workerNodeKey,
869 this.dequeueTask(workerNodeKey) as Task<Data>
870 )
ff733df7 871 }
ff733df7
JB
872 }
873 }
874
ef41a6e6
JB
875 private flushTasksQueues (): void {
876 for (const [workerNodeKey] of this.workerNodes.entries()) {
877 this.flushTasksQueue(workerNodeKey)
878 }
879 }
b6b32453
JB
880
881 private setWorkerStatistics (worker: Worker): void {
882 this.sendToWorker(worker, {
883 statistics: {
87de9ff5
JB
884 runTime:
885 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 886 .runTime.aggregate,
87de9ff5 887 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
5df69fab 888 .elu.aggregate
b6b32453
JB
889 }
890 })
891 }
8604aaab
JB
892
893 private getWorkerUsage (worker: Worker): WorkerUsage {
894 return {
1c6fe997 895 tasks: this.getTaskStatistics(worker),
8604aaab 896 runTime: {
932fc8be 897 aggregate: 0,
8604aaab
JB
898 average: 0,
899 median: 0,
900 history: new CircularArray()
901 },
902 waitTime: {
932fc8be 903 aggregate: 0,
8604aaab
JB
904 average: 0,
905 median: 0,
906 history: new CircularArray()
907 },
5df69fab
JB
908 elu: {
909 idle: {
910 aggregate: 0,
911 average: 0,
912 median: 0,
913 history: new CircularArray()
914 },
915 active: {
916 aggregate: 0,
917 average: 0,
918 median: 0,
919 history: new CircularArray()
920 },
921 utilization: 0
922 }
8604aaab
JB
923 }
924 }
925
1c6fe997
JB
926 private getTaskStatistics (worker: Worker): TaskStatistics {
927 const queueSize =
928 this.workerNodes[this.getWorkerNodeKey(worker)]?.tasksQueue?.size
8604aaab
JB
929 return {
930 executed: 0,
931 executing: 0,
932 get queued (): number {
1c6fe997 933 return queueSize ?? 0
8604aaab
JB
934 },
935 failed: 0
936 }
937 }
c97c7edb 938}