refactor: factor out dynamic worker creation
[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
c2ade475 382 protected internalBusy (): boolean {
e0ae6100
JB
383 return (
384 this.workerNodes.findIndex(workerNode => {
a4e07f72 385 return workerNode.workerUsage.tasks.executing === 0
e0ae6100
JB
386 }) === -1
387 )
cb70b19d
JB
388 }
389
afc003b2 390 /** @inheritDoc */
a86b6df1 391 public async execute (data?: Data, name?: string): Promise<Response> {
b6b32453 392 const timestamp = performance.now()
20dcad1a 393 const workerNodeKey = this.chooseWorkerNode()
adc3c320 394 const submittedTask: Task<Data> = {
a86b6df1 395 name,
e5a5c0fc
JB
396 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
397 data: data ?? ({} as Data),
b6b32453 398 timestamp,
adc3c320
JB
399 id: crypto.randomUUID()
400 }
2e81254d 401 const res = new Promise<Response>((resolve, reject) => {
02706357 402 this.promiseResponseMap.set(submittedTask.id as string, {
2e81254d
JB
403 resolve,
404 reject,
20dcad1a 405 worker: this.workerNodes[workerNodeKey].worker
2e81254d
JB
406 })
407 })
ff733df7
JB
408 if (
409 this.opts.enableTasksQueue === true &&
7171d33f 410 (this.busy ||
a4e07f72 411 this.workerNodes[workerNodeKey].workerUsage.tasks.executing >=
7171d33f 412 ((this.opts.tasksQueueOptions as TasksQueueOptions)
3528c992 413 .concurrency as number))
ff733df7 414 ) {
26a929d7
JB
415 this.enqueueTask(workerNodeKey, submittedTask)
416 } else {
2e81254d 417 this.executeTask(workerNodeKey, submittedTask)
adc3c320 418 }
b0d6ed8f 419 this.workerChoiceStrategyContext.update(workerNodeKey)
ff733df7 420 this.checkAndEmitEvents()
78cea37e 421 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
422 return res
423 }
c97c7edb 424
afc003b2 425 /** @inheritDoc */
c97c7edb 426 public async destroy (): Promise<void> {
1fbcaa7c 427 await Promise.all(
875a7c37
JB
428 this.workerNodes.map(async (workerNode, workerNodeKey) => {
429 this.flushTasksQueue(workerNodeKey)
47aacbaa 430 // FIXME: wait for tasks to be finished
f06e48d8 431 await this.destroyWorker(workerNode.worker)
1fbcaa7c
JB
432 })
433 )
c97c7edb
S
434 }
435
4a6952ff 436 /**
f06e48d8 437 * Shutdowns the given worker.
4a6952ff 438 *
f06e48d8 439 * @param worker - A worker within `workerNodes`.
4a6952ff
JB
440 */
441 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 442
729c563d 443 /**
2e81254d 444 * Setup hook to execute code before worker node are created in the abstract constructor.
d99ba5a8 445 * Can be overridden
afc003b2
JB
446 *
447 * @virtual
729c563d 448 */
280c2a77 449 protected setupHook (): void {
d99ba5a8 450 // Intentionally empty
280c2a77 451 }
c97c7edb 452
729c563d 453 /**
280c2a77
S
454 * Should return whether the worker is the main worker or not.
455 */
456 protected abstract isMain (): boolean
457
458 /**
2e81254d 459 * Hook executed before the worker task execution.
bf9549ae 460 * Can be overridden.
729c563d 461 *
f06e48d8 462 * @param workerNodeKey - The worker node key.
1c6fe997 463 * @param task - The task to execute.
729c563d 464 */
1c6fe997
JB
465 protected beforeTaskExecutionHook (
466 workerNodeKey: number,
467 task: Task<Data>
468 ): void {
469 const workerUsage = this.workerNodes[workerNodeKey].workerUsage
470 ++workerUsage.tasks.executing
471 this.updateWaitTimeWorkerUsage(workerUsage, task)
c97c7edb
S
472 }
473
c01733f1 474 /**
2e81254d 475 * Hook executed after the worker task execution.
bf9549ae 476 * Can be overridden.
c01733f1 477 *
c923ce56 478 * @param worker - The worker.
38e795c1 479 * @param message - The received message.
c01733f1 480 */
2e81254d 481 protected afterTaskExecutionHook (
c923ce56 482 worker: Worker,
2740a743 483 message: MessageValue<Response>
bf9549ae 484 ): void {
a4e07f72
JB
485 const workerUsage =
486 this.workerNodes[this.getWorkerNodeKey(worker)].workerUsage
f1c06930
JB
487 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
488 this.updateRunTimeWorkerUsage(workerUsage, message)
489 this.updateEluWorkerUsage(workerUsage, message)
490 }
491
492 private updateTaskStatisticsWorkerUsage (
493 workerUsage: WorkerUsage,
494 message: MessageValue<Response>
495 ): void {
a4e07f72
JB
496 const workerTaskStatistics = workerUsage.tasks
497 --workerTaskStatistics.executing
498 ++workerTaskStatistics.executed
82f36766 499 if (message.taskError != null) {
a4e07f72 500 ++workerTaskStatistics.failed
2740a743 501 }
f8eb0a2a
JB
502 }
503
a4e07f72
JB
504 private updateRunTimeWorkerUsage (
505 workerUsage: WorkerUsage,
f8eb0a2a
JB
506 message: MessageValue<Response>
507 ): void {
87de9ff5
JB
508 if (
509 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
932fc8be 510 .aggregate
87de9ff5 511 ) {
932fc8be 512 workerUsage.runTime.aggregate += message.taskPerformance?.runTime ?? 0
c6bd2650 513 if (
932fc8be
JB
514 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
515 .average &&
a4e07f72 516 workerUsage.tasks.executed !== 0
c6bd2650 517 ) {
a4e07f72 518 workerUsage.runTime.average =
f1c06930
JB
519 workerUsage.runTime.aggregate /
520 (workerUsage.tasks.executed - workerUsage.tasks.failed)
3032893a 521 }
3fa4cdd2 522 if (
932fc8be
JB
523 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
524 .median &&
d715b7bc 525 message.taskPerformance?.runTime != null
3fa4cdd2 526 ) {
a4e07f72
JB
527 workerUsage.runTime.history.push(message.taskPerformance.runTime)
528 workerUsage.runTime.median = median(workerUsage.runTime.history)
78099a15 529 }
3032893a 530 }
f8eb0a2a
JB
531 }
532
a4e07f72
JB
533 private updateWaitTimeWorkerUsage (
534 workerUsage: WorkerUsage,
1c6fe997 535 task: Task<Data>
f8eb0a2a 536 ): void {
1c6fe997
JB
537 const timestamp = performance.now()
538 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
87de9ff5
JB
539 if (
540 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime
932fc8be 541 .aggregate
87de9ff5 542 ) {
932fc8be 543 workerUsage.waitTime.aggregate += taskWaitTime ?? 0
09a6305f 544 if (
87de9ff5 545 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 546 .waitTime.average &&
a4e07f72 547 workerUsage.tasks.executed !== 0
09a6305f 548 ) {
a4e07f72 549 workerUsage.waitTime.average =
f1c06930
JB
550 workerUsage.waitTime.aggregate /
551 (workerUsage.tasks.executed - workerUsage.tasks.failed)
09a6305f
JB
552 }
553 if (
87de9ff5 554 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 555 .waitTime.median &&
1c6fe997 556 taskWaitTime != null
09a6305f 557 ) {
1c6fe997 558 workerUsage.waitTime.history.push(taskWaitTime)
a4e07f72 559 workerUsage.waitTime.median = median(workerUsage.waitTime.history)
09a6305f 560 }
0567595a 561 }
c01733f1 562 }
563
a4e07f72 564 private updateEluWorkerUsage (
5df69fab 565 workerUsage: WorkerUsage,
62c15a68
JB
566 message: MessageValue<Response>
567 ): void {
5df69fab
JB
568 if (
569 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
570 .aggregate
571 ) {
572 if (workerUsage.elu != null && message.taskPerformance?.elu != null) {
9adcefab
JB
573 workerUsage.elu.idle.aggregate += message.taskPerformance.elu.idle
574 workerUsage.elu.active.aggregate += message.taskPerformance.elu.active
5df69fab
JB
575 workerUsage.elu.utilization =
576 (workerUsage.elu.utilization +
577 message.taskPerformance.elu.utilization) /
578 2
579 } else if (message.taskPerformance?.elu != null) {
580 workerUsage.elu.idle.aggregate = message.taskPerformance.elu.idle
581 workerUsage.elu.active.aggregate = message.taskPerformance.elu.active
582 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
583 }
d715b7bc 584 if (
5df69fab
JB
585 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
586 .average &&
587 workerUsage.tasks.executed !== 0
588 ) {
f1c06930
JB
589 const executedTasks =
590 workerUsage.tasks.executed - workerUsage.tasks.failed
5df69fab 591 workerUsage.elu.idle.average =
f1c06930 592 workerUsage.elu.idle.aggregate / executedTasks
5df69fab 593 workerUsage.elu.active.average =
f1c06930 594 workerUsage.elu.active.aggregate / executedTasks
5df69fab
JB
595 }
596 if (
597 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
598 .median &&
d715b7bc
JB
599 message.taskPerformance?.elu != null
600 ) {
5df69fab
JB
601 workerUsage.elu.idle.history.push(message.taskPerformance.elu.idle)
602 workerUsage.elu.active.history.push(message.taskPerformance.elu.active)
603 workerUsage.elu.idle.median = median(workerUsage.elu.idle.history)
604 workerUsage.elu.active.median = median(workerUsage.elu.active.history)
62c15a68
JB
605 }
606 }
607 }
608
280c2a77 609 /**
f06e48d8 610 * Chooses a worker node for the next task.
280c2a77 611 *
20dcad1a 612 * The default worker choice strategy uses a round robin algorithm to distribute the load.
280c2a77 613 *
20dcad1a 614 * @returns The worker node key
280c2a77 615 */
20dcad1a 616 protected chooseWorkerNode (): number {
930dcf12
JB
617 if (this.shallCreateDynamicWorker()) {
618 return this.getWorkerNodeKey(this.createAndSetupDynamicWorker())
17393ac8 619 }
930dcf12
JB
620 return this.workerChoiceStrategyContext.execute()
621 }
622
623 protected shallCreateDynamicWorker (): boolean {
624 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
c97c7edb
S
625 }
626
280c2a77 627 /**
675bb809 628 * Sends a message to the given worker.
280c2a77 629 *
38e795c1
JB
630 * @param worker - The worker which should receive the message.
631 * @param message - The message.
280c2a77
S
632 */
633 protected abstract sendToWorker (
634 worker: Worker,
635 message: MessageValue<Data>
636 ): void
637
4a6952ff 638 /**
f06e48d8 639 * Registers a listener callback on the given worker.
4a6952ff 640 *
38e795c1
JB
641 * @param worker - The worker which should register a listener.
642 * @param listener - The message listener callback.
4a6952ff
JB
643 */
644 protected abstract registerWorkerMessageListener<
4f7fa42a 645 Message extends Data | Response
78cea37e 646 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 647
729c563d
S
648 /**
649 * Returns a newly created worker.
650 */
280c2a77 651 protected abstract createWorker (): Worker
c97c7edb 652
729c563d 653 /**
f06e48d8 654 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
729c563d 655 *
38e795c1 656 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 657 *
38e795c1 658 * @param worker - The newly created worker.
729c563d 659 */
280c2a77 660 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 661
4a6952ff 662 /**
f06e48d8 663 * Creates a new worker and sets it up completely in the pool worker nodes.
4a6952ff
JB
664 *
665 * @returns New, completely set up worker.
666 */
667 protected createAndSetupWorker (): Worker {
bdacc2d2 668 const worker = this.createWorker()
280c2a77 669
35cf1c03 670 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba 671 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
1f68cede
JB
672 worker.on('error', error => {
673 if (this.emitter != null) {
674 this.emitter.emit(PoolEvents.error, error)
675 }
5baee0d7 676 if (this.opts.restartWorkerOnError === true) {
1f68cede 677 this.createAndSetupWorker()
5baee0d7
JB
678 }
679 })
a35560ba
S
680 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
681 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 682 worker.once('exit', () => {
f06e48d8 683 this.removeWorkerNode(worker)
a974afa6 684 })
280c2a77 685
f06e48d8 686 this.pushWorkerNode(worker)
280c2a77 687
b6b32453
JB
688 this.setWorkerStatistics(worker)
689
280c2a77
S
690 this.afterWorkerSetup(worker)
691
c97c7edb
S
692 return worker
693 }
be0676b3 694
930dcf12
JB
695 /**
696 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
697 *
698 * @returns New, completely set up dynamic worker.
699 */
700 protected createAndSetupDynamicWorker (): Worker {
701 const worker = this.createAndSetupWorker()
702 this.registerWorkerMessageListener(worker, message => {
703 const currentWorkerNodeKey = this.getWorkerNodeKey(worker)
704 if (
705 isKillBehavior(KillBehaviors.HARD, message.kill) ||
706 (message.kill != null &&
707 this.workerNodes[currentWorkerNodeKey].workerUsage.tasks.executing ===
708 0)
709 ) {
710 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
711 this.flushTasksQueue(currentWorkerNodeKey)
712 // FIXME: wait for tasks to be finished
713 void (this.destroyWorker(worker) as Promise<void>)
714 }
715 })
716 return worker
717 }
718
be0676b3 719 /**
ff733df7 720 * This function is the listener registered for each worker message.
be0676b3 721 *
bdacc2d2 722 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
723 */
724 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 725 return message => {
b1989cfd 726 if (message.id != null) {
a3445496 727 // Task execution response received
2740a743 728 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 729 if (promiseResponse != null) {
82f36766
JB
730 if (message.taskError != null) {
731 promiseResponse.reject(message.taskError.message)
91ee39ed 732 if (this.emitter != null) {
82f36766 733 this.emitter.emit(PoolEvents.taskError, message.taskError)
91ee39ed 734 }
a05c10de 735 } else {
2740a743 736 promiseResponse.resolve(message.data as Response)
a05c10de 737 }
2e81254d 738 this.afterTaskExecutionHook(promiseResponse.worker, message)
2740a743 739 this.promiseResponseMap.delete(message.id)
ff733df7
JB
740 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
741 if (
742 this.opts.enableTasksQueue === true &&
416fd65c 743 this.tasksQueueSize(workerNodeKey) > 0
ff733df7 744 ) {
2e81254d
JB
745 this.executeTask(
746 workerNodeKey,
ff733df7
JB
747 this.dequeueTask(workerNodeKey) as Task<Data>
748 )
749 }
be0676b3
APA
750 }
751 }
752 }
be0676b3 753 }
7c0ba920 754
ff733df7 755 private checkAndEmitEvents (): void {
1f68cede 756 if (this.emitter != null) {
ff733df7 757 if (this.busy) {
6b27d407 758 this.emitter?.emit(PoolEvents.busy, this.info)
ff733df7 759 }
6b27d407
JB
760 if (this.type === PoolTypes.dynamic && this.full) {
761 this.emitter?.emit(PoolEvents.full, this.info)
ff733df7 762 }
164d950a
JB
763 }
764 }
765
0ebe2a9f
JB
766 /**
767 * Sets the given worker node its tasks usage in the pool.
768 *
769 * @param workerNode - The worker node.
a4e07f72 770 * @param workerUsage - The worker usage.
0ebe2a9f
JB
771 */
772 private setWorkerNodeTasksUsage (
773 workerNode: WorkerNode<Worker, Data>,
a4e07f72 774 workerUsage: WorkerUsage
0ebe2a9f 775 ): void {
a4e07f72 776 workerNode.workerUsage = workerUsage
0ebe2a9f
JB
777 }
778
a05c10de 779 /**
f06e48d8 780 * Pushes the given worker in the pool worker nodes.
ea7a90d3 781 *
38e795c1 782 * @param worker - The worker.
f06e48d8 783 * @returns The worker nodes length.
ea7a90d3 784 */
f06e48d8
JB
785 private pushWorkerNode (worker: Worker): number {
786 return this.workerNodes.push({
ffcbbad8 787 worker,
8604aaab 788 workerUsage: this.getWorkerUsage(worker),
29ee7e9a 789 tasksQueue: new Queue<Task<Data>>()
ea7a90d3
JB
790 })
791 }
c923ce56 792
8604aaab
JB
793 // /**
794 // * Sets the given worker in the pool worker nodes.
795 // *
796 // * @param workerNodeKey - The worker node key.
797 // * @param worker - The worker.
798 // * @param workerUsage - The worker usage.
799 // * @param tasksQueue - The worker task queue.
800 // */
801 // private setWorkerNode (
802 // workerNodeKey: number,
803 // worker: Worker,
804 // workerUsage: WorkerUsage,
805 // tasksQueue: Queue<Task<Data>>
806 // ): void {
807 // this.workerNodes[workerNodeKey] = {
808 // worker,
809 // workerUsage,
810 // tasksQueue
811 // }
812 // }
51fe3d3c
JB
813
814 /**
f06e48d8 815 * Removes the given worker from the pool worker nodes.
51fe3d3c 816 *
f06e48d8 817 * @param worker - The worker.
51fe3d3c 818 */
416fd65c 819 private removeWorkerNode (worker: Worker): void {
f06e48d8 820 const workerNodeKey = this.getWorkerNodeKey(worker)
1f68cede
JB
821 if (workerNodeKey !== -1) {
822 this.workerNodes.splice(workerNodeKey, 1)
823 this.workerChoiceStrategyContext.remove(workerNodeKey)
824 }
51fe3d3c 825 }
adc3c320 826
2e81254d 827 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1c6fe997 828 this.beforeTaskExecutionHook(workerNodeKey, task)
2e81254d
JB
829 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
830 }
831
f9f00b5f 832 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
29ee7e9a 833 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
adc3c320
JB
834 }
835
416fd65c 836 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
29ee7e9a 837 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
adc3c320
JB
838 }
839
416fd65c 840 private tasksQueueSize (workerNodeKey: number): number {
4d8bf9e4 841 return this.workerNodes[workerNodeKey].tasksQueue.size
adc3c320 842 }
ff733df7 843
416fd65c
JB
844 private flushTasksQueue (workerNodeKey: number): void {
845 if (this.tasksQueueSize(workerNodeKey) > 0) {
29ee7e9a
JB
846 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
847 this.executeTask(
848 workerNodeKey,
849 this.dequeueTask(workerNodeKey) as Task<Data>
850 )
ff733df7 851 }
ff733df7
JB
852 }
853 }
854
ef41a6e6
JB
855 private flushTasksQueues (): void {
856 for (const [workerNodeKey] of this.workerNodes.entries()) {
857 this.flushTasksQueue(workerNodeKey)
858 }
859 }
b6b32453
JB
860
861 private setWorkerStatistics (worker: Worker): void {
862 this.sendToWorker(worker, {
863 statistics: {
87de9ff5
JB
864 runTime:
865 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
932fc8be 866 .runTime.aggregate,
87de9ff5 867 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
5df69fab 868 .elu.aggregate
b6b32453
JB
869 }
870 })
871 }
8604aaab
JB
872
873 private getWorkerUsage (worker: Worker): WorkerUsage {
874 return {
1c6fe997 875 tasks: this.getTaskStatistics(worker),
8604aaab 876 runTime: {
932fc8be 877 aggregate: 0,
8604aaab
JB
878 average: 0,
879 median: 0,
880 history: new CircularArray()
881 },
882 waitTime: {
932fc8be 883 aggregate: 0,
8604aaab
JB
884 average: 0,
885 median: 0,
886 history: new CircularArray()
887 },
5df69fab
JB
888 elu: {
889 idle: {
890 aggregate: 0,
891 average: 0,
892 median: 0,
893 history: new CircularArray()
894 },
895 active: {
896 aggregate: 0,
897 average: 0,
898 median: 0,
899 history: new CircularArray()
900 },
901 utilization: 0
902 }
8604aaab
JB
903 }
904 }
905
1c6fe997
JB
906 private getTaskStatistics (worker: Worker): TaskStatistics {
907 const queueSize =
908 this.workerNodes[this.getWorkerNodeKey(worker)]?.tasksQueue?.size
8604aaab
JB
909 return {
910 executed: 0,
911 executing: 0,
912 get queued (): number {
1c6fe997 913 return queueSize ?? 0
8604aaab
JB
914 },
915 failed: 0
916 }
917 }
c97c7edb 918}