Merge pull request #747 from poolifier/multiple-functions
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
2740a743 2import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
bbeadd16
JB
3import {
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
5 EMPTY_FUNCTION,
6 median
7} from '../utils'
34a0cfab 8import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
65d7a1c9 9import { CircularArray } from '../circular-array'
29ee7e9a 10import { Queue } from '../queue'
c4855468 11import {
65d7a1c9 12 type IPool,
7c5a1080 13 PoolEmitter,
c4855468 14 PoolEvents,
c4855468 15 type PoolOptions,
65d7a1c9
JB
16 PoolType,
17 type TasksQueueOptions
c4855468 18} from './pool'
f06e48d8 19import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
a35560ba
S
20import {
21 WorkerChoiceStrategies,
a20f0ba5
JB
22 type WorkerChoiceStrategy,
23 type WorkerChoiceStrategyOptions
bdaf31cd
JB
24} from './selection-strategies/selection-strategies-types'
25import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 26
729c563d 27/**
ea7a90d3 28 * Base class that implements some shared logic for all poolifier pools.
729c563d 29 *
38e795c1
JB
30 * @typeParam Worker - Type of worker which manages this pool.
31 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 32 * @typeParam Response - Type of execution response. This can only be serializable data.
729c563d 33 */
c97c7edb 34export abstract class AbstractPool<
f06e48d8 35 Worker extends IWorker,
d3c8a1a8
S
36 Data = unknown,
37 Response = unknown
c4855468 38> implements IPool<Worker, Data, Response> {
afc003b2 39 /** @inheritDoc */
f06e48d8 40 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
4a6952ff 41
afc003b2 42 /** @inheritDoc */
7c0ba920
JB
43 public readonly emitter?: PoolEmitter
44
be0676b3 45 /**
a3445496 46 * The execution response promise map.
be0676b3 47 *
2740a743 48 * - `key`: The message id of each submitted task.
a3445496 49 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
be0676b3 50 *
a3445496 51 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 52 */
c923ce56
JB
53 protected promiseResponseMap: Map<
54 string,
55 PromiseResponseWrapper<Worker, Response>
56 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
c97c7edb 57
a35560ba 58 /**
51fe3d3c 59 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba 60 *
51fe3d3c 61 * Default to a round robin algorithm.
a35560ba
S
62 */
63 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
64 Worker,
65 Data,
66 Response
a35560ba
S
67 >
68
729c563d
S
69 /**
70 * Constructs a new poolifier pool.
71 *
38e795c1 72 * @param numberOfWorkers - Number of workers that this pool should manage.
029715f0 73 * @param filePath - Path to the worker file.
38e795c1 74 * @param opts - Options for the pool.
729c563d 75 */
c97c7edb 76 public constructor (
5c5a1fb7 77 public readonly numberOfWorkers: number,
c97c7edb 78 public readonly filePath: string,
1927ee67 79 public readonly opts: PoolOptions<Worker>
c97c7edb 80 ) {
78cea37e 81 if (!this.isMain()) {
c97c7edb
S
82 throw new Error('Cannot start a pool from a worker!')
83 }
8d3782fa 84 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 85 this.checkFilePath(this.filePath)
7c0ba920 86 this.checkPoolOptions(this.opts)
1086026a 87
7254e419
JB
88 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
89 this.executeTask = this.executeTask.bind(this)
90 this.enqueueTask = this.enqueueTask.bind(this)
91 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
1086026a 92
c97c7edb
S
93 this.setupHook()
94
5c5a1fb7 95 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 96 this.createAndSetupWorker()
c97c7edb
S
97 }
98
6bd72cd0 99 if (this.opts.enableEvents === true) {
7c0ba920
JB
100 this.emitter = new PoolEmitter()
101 }
d59df138
JB
102 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
103 Worker,
104 Data,
105 Response
da309861
JB
106 >(
107 this,
108 this.opts.workerChoiceStrategy,
109 this.opts.workerChoiceStrategyOptions
110 )
c97c7edb
S
111 }
112
a35560ba 113 private checkFilePath (filePath: string): void {
ffcbbad8
JB
114 if (
115 filePath == null ||
116 (typeof filePath === 'string' && filePath.trim().length === 0)
117 ) {
c510fea7
APA
118 throw new Error('Please specify a file with a worker implementation')
119 }
120 }
121
8d3782fa
JB
122 private checkNumberOfWorkers (numberOfWorkers: number): void {
123 if (numberOfWorkers == null) {
124 throw new Error(
125 'Cannot instantiate a pool without specifying the number of workers'
126 )
78cea37e 127 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 128 throw new TypeError(
8d3782fa
JB
129 'Cannot instantiate a pool with a non integer number of workers'
130 )
131 } else if (numberOfWorkers < 0) {
473c717a 132 throw new RangeError(
8d3782fa
JB
133 'Cannot instantiate a pool with a negative number of workers'
134 )
7c0ba920 135 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
136 throw new Error('Cannot instantiate a fixed pool with no worker')
137 }
138 }
139
7c0ba920 140 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
141 this.opts.workerChoiceStrategy =
142 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
aee46736 143 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
da309861 144 this.opts.workerChoiceStrategyOptions =
bbeadd16 145 opts.workerChoiceStrategyOptions ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
aee46736 146 this.opts.enableEvents = opts.enableEvents ?? true
ff733df7 147 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
7171d33f 148 if (this.opts.enableTasksQueue) {
a20f0ba5
JB
149 this.checkValidTasksQueueOptions(
150 opts.tasksQueueOptions as TasksQueueOptions
151 )
152 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
153 opts.tasksQueueOptions as TasksQueueOptions
154 )
7171d33f 155 }
aee46736
JB
156 }
157
158 private checkValidWorkerChoiceStrategy (
159 workerChoiceStrategy: WorkerChoiceStrategy
160 ): void {
161 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
b529c323 162 throw new Error(
aee46736 163 `Invalid worker choice strategy '${workerChoiceStrategy}'`
b529c323
JB
164 )
165 }
7c0ba920
JB
166 }
167
a20f0ba5
JB
168 private checkValidTasksQueueOptions (
169 tasksQueueOptions: TasksQueueOptions
170 ): void {
171 if ((tasksQueueOptions?.concurrency as number) <= 0) {
172 throw new Error(
173 `Invalid worker tasks concurrency '${
174 tasksQueueOptions.concurrency as number
175 }'`
176 )
177 }
178 }
179
afc003b2 180 /** @inheritDoc */
7c0ba920
JB
181 public abstract get type (): PoolType
182
c2ade475 183 /**
ff733df7 184 * Number of tasks running in the pool.
c2ade475
JB
185 */
186 private get numberOfRunningTasks (): number {
ff733df7
JB
187 return this.workerNodes.reduce(
188 (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
189 0
190 )
191 }
192
193 /**
194 * Number of tasks queued in the pool.
195 */
196 private get numberOfQueuedTasks (): number {
197 if (this.opts.enableTasksQueue === false) {
198 return 0
199 }
200 return this.workerNodes.reduce(
4d8bf9e4 201 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
ff733df7
JB
202 0
203 )
a35560ba
S
204 }
205
ffcbbad8 206 /**
f06e48d8 207 * Gets the given worker its worker node key.
ffcbbad8
JB
208 *
209 * @param worker - The worker.
f06e48d8 210 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
ffcbbad8 211 */
f06e48d8
JB
212 private getWorkerNodeKey (worker: Worker): number {
213 return this.workerNodes.findIndex(
214 workerNode => workerNode.worker === worker
215 )
bf9549ae
JB
216 }
217
afc003b2 218 /** @inheritDoc */
a35560ba 219 public setWorkerChoiceStrategy (
59219cbb
JB
220 workerChoiceStrategy: WorkerChoiceStrategy,
221 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 222 ): void {
aee46736 223 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
b98ec2e6 224 this.opts.workerChoiceStrategy = workerChoiceStrategy
0ebe2a9f 225 for (const workerNode of this.workerNodes) {
f82cd357
JB
226 this.setWorkerNodeTasksUsage(workerNode, {
227 run: 0,
228 running: 0,
229 runTime: 0,
230 runTimeHistory: new CircularArray(),
231 avgRunTime: 0,
232 medRunTime: 0,
233 error: 0
234 })
ea7a90d3 235 }
a35560ba 236 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
a20f0ba5
JB
237 this.opts.workerChoiceStrategy
238 )
59219cbb
JB
239 if (workerChoiceStrategyOptions != null) {
240 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
241 }
a20f0ba5
JB
242 }
243
244 /** @inheritDoc */
245 public setWorkerChoiceStrategyOptions (
246 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
247 ): void {
248 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
249 this.workerChoiceStrategyContext.setOptions(
250 this.opts.workerChoiceStrategyOptions
a35560ba
S
251 )
252 }
253
a20f0ba5 254 /** @inheritDoc */
8f52842f
JB
255 public enableTasksQueue (
256 enable: boolean,
257 tasksQueueOptions?: TasksQueueOptions
258 ): void {
a20f0ba5 259 if (this.opts.enableTasksQueue === true && !enable) {
ef41a6e6 260 this.flushTasksQueues()
a20f0ba5
JB
261 }
262 this.opts.enableTasksQueue = enable
8f52842f 263 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
a20f0ba5
JB
264 }
265
266 /** @inheritDoc */
8f52842f 267 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
a20f0ba5 268 if (this.opts.enableTasksQueue === true) {
8f52842f
JB
269 this.checkValidTasksQueueOptions(tasksQueueOptions)
270 this.opts.tasksQueueOptions =
271 this.buildTasksQueueOptions(tasksQueueOptions)
a20f0ba5
JB
272 } else {
273 delete this.opts.tasksQueueOptions
274 }
275 }
276
277 private buildTasksQueueOptions (
278 tasksQueueOptions: TasksQueueOptions
279 ): TasksQueueOptions {
280 return {
281 concurrency: tasksQueueOptions?.concurrency ?? 1
282 }
283 }
284
c319c66b
JB
285 /**
286 * Whether the pool is full or not.
287 *
288 * The pool filling boolean status.
289 */
290 protected abstract get full (): boolean
c2ade475 291
c319c66b
JB
292 /**
293 * Whether the pool is busy or not.
294 *
295 * The pool busyness boolean status.
296 */
297 protected abstract get busy (): boolean
7c0ba920 298
c2ade475 299 protected internalBusy (): boolean {
e0ae6100
JB
300 return (
301 this.workerNodes.findIndex(workerNode => {
302 return workerNode.tasksUsage?.running === 0
303 }) === -1
304 )
cb70b19d
JB
305 }
306
afc003b2 307 /** @inheritDoc */
a86b6df1 308 public async execute (data?: Data, name?: string): Promise<Response> {
adc3c320
JB
309 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
310 const submittedTask: Task<Data> = {
a86b6df1 311 name,
e5a5c0fc
JB
312 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
313 data: data ?? ({} as Data),
adc3c320
JB
314 id: crypto.randomUUID()
315 }
2e81254d 316 const res = new Promise<Response>((resolve, reject) => {
02706357 317 this.promiseResponseMap.set(submittedTask.id as string, {
2e81254d
JB
318 resolve,
319 reject,
320 worker: workerNode.worker
321 })
322 })
ff733df7
JB
323 if (
324 this.opts.enableTasksQueue === true &&
7171d33f 325 (this.busy ||
3528c992 326 this.workerNodes[workerNodeKey].tasksUsage.running >=
7171d33f 327 ((this.opts.tasksQueueOptions as TasksQueueOptions)
3528c992 328 .concurrency as number))
ff733df7 329 ) {
26a929d7
JB
330 this.enqueueTask(workerNodeKey, submittedTask)
331 } else {
2e81254d 332 this.executeTask(workerNodeKey, submittedTask)
adc3c320 333 }
ff733df7 334 this.checkAndEmitEvents()
78cea37e 335 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
336 return res
337 }
c97c7edb 338
afc003b2 339 /** @inheritDoc */
c97c7edb 340 public async destroy (): Promise<void> {
1fbcaa7c 341 await Promise.all(
875a7c37
JB
342 this.workerNodes.map(async (workerNode, workerNodeKey) => {
343 this.flushTasksQueue(workerNodeKey)
f06e48d8 344 await this.destroyWorker(workerNode.worker)
1fbcaa7c
JB
345 })
346 )
c97c7edb
S
347 }
348
4a6952ff 349 /**
f06e48d8 350 * Shutdowns the given worker.
4a6952ff 351 *
f06e48d8 352 * @param worker - A worker within `workerNodes`.
4a6952ff
JB
353 */
354 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 355
729c563d 356 /**
2e81254d 357 * Setup hook to execute code before worker node are created in the abstract constructor.
d99ba5a8 358 * Can be overridden
afc003b2
JB
359 *
360 * @virtual
729c563d 361 */
280c2a77 362 protected setupHook (): void {
d99ba5a8 363 // Intentionally empty
280c2a77 364 }
c97c7edb 365
729c563d 366 /**
280c2a77
S
367 * Should return whether the worker is the main worker or not.
368 */
369 protected abstract isMain (): boolean
370
371 /**
2e81254d 372 * Hook executed before the worker task execution.
bf9549ae 373 * Can be overridden.
729c563d 374 *
f06e48d8 375 * @param workerNodeKey - The worker node key.
729c563d 376 */
2e81254d 377 protected beforeTaskExecutionHook (workerNodeKey: number): void {
f06e48d8 378 ++this.workerNodes[workerNodeKey].tasksUsage.running
c97c7edb
S
379 }
380
c01733f1 381 /**
2e81254d 382 * Hook executed after the worker task execution.
bf9549ae 383 * Can be overridden.
c01733f1 384 *
c923ce56 385 * @param worker - The worker.
38e795c1 386 * @param message - The received message.
c01733f1 387 */
2e81254d 388 protected afterTaskExecutionHook (
c923ce56 389 worker: Worker,
2740a743 390 message: MessageValue<Response>
bf9549ae 391 ): void {
05ca3d0d 392 const workerTasksUsage = this.getWorkerTasksUsage(worker)
3032893a
JB
393 --workerTasksUsage.running
394 ++workerTasksUsage.run
2740a743
JB
395 if (message.error != null) {
396 ++workerTasksUsage.error
397 }
97a2abc3 398 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
aee46736 399 workerTasksUsage.runTime += message.runTime ?? 0
c6bd2650
JB
400 if (
401 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
402 workerTasksUsage.run !== 0
403 ) {
3032893a
JB
404 workerTasksUsage.avgRunTime =
405 workerTasksUsage.runTime / workerTasksUsage.run
406 }
78099a15
JB
407 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
408 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
409 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
410 }
3032893a 411 }
c01733f1 412 }
413
280c2a77 414 /**
f06e48d8 415 * Chooses a worker node for the next task.
280c2a77 416 *
51fe3d3c 417 * The default uses a round robin algorithm to distribute the load.
280c2a77 418 *
adc3c320 419 * @returns [worker node key, worker node].
280c2a77 420 */
adc3c320 421 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
f06e48d8 422 let workerNodeKey: number
0527b6db 423 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
adc3c320
JB
424 const workerCreated = this.createAndSetupWorker()
425 this.registerWorkerMessageListener(workerCreated, message => {
17393ac8
JB
426 if (
427 isKillBehavior(KillBehaviors.HARD, message.kill) ||
d2097c13 428 (message.kill != null &&
adc3c320 429 this.getWorkerTasksUsage(workerCreated)?.running === 0)
17393ac8 430 ) {
ff733df7
JB
431 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
432 this.flushTasksQueueByWorker(workerCreated)
7c5a1080 433 void (this.destroyWorker(workerCreated) as Promise<void>)
17393ac8
JB
434 }
435 })
adc3c320 436 workerNodeKey = this.getWorkerNodeKey(workerCreated)
17393ac8 437 } else {
f06e48d8 438 workerNodeKey = this.workerChoiceStrategyContext.execute()
17393ac8 439 }
adc3c320 440 return [workerNodeKey, this.workerNodes[workerNodeKey]]
c97c7edb
S
441 }
442
280c2a77 443 /**
675bb809 444 * Sends a message to the given worker.
280c2a77 445 *
38e795c1
JB
446 * @param worker - The worker which should receive the message.
447 * @param message - The message.
280c2a77
S
448 */
449 protected abstract sendToWorker (
450 worker: Worker,
451 message: MessageValue<Data>
452 ): void
453
4a6952ff 454 /**
f06e48d8 455 * Registers a listener callback on the given worker.
4a6952ff 456 *
38e795c1
JB
457 * @param worker - The worker which should register a listener.
458 * @param listener - The message listener callback.
4a6952ff
JB
459 */
460 protected abstract registerWorkerMessageListener<
4f7fa42a 461 Message extends Data | Response
78cea37e 462 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 463
729c563d
S
464 /**
465 * Returns a newly created worker.
466 */
280c2a77 467 protected abstract createWorker (): Worker
c97c7edb 468
729c563d 469 /**
f06e48d8 470 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
729c563d 471 *
38e795c1 472 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 473 *
38e795c1 474 * @param worker - The newly created worker.
729c563d 475 */
280c2a77 476 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 477
4a6952ff 478 /**
f06e48d8 479 * Creates a new worker and sets it up completely in the pool worker nodes.
4a6952ff
JB
480 *
481 * @returns New, completely set up worker.
482 */
483 protected createAndSetupWorker (): Worker {
bdacc2d2 484 const worker = this.createWorker()
280c2a77 485
35cf1c03 486 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
487 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
488 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
489 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 490 worker.once('exit', () => {
f06e48d8 491 this.removeWorkerNode(worker)
a974afa6 492 })
280c2a77 493
f06e48d8 494 this.pushWorkerNode(worker)
280c2a77
S
495
496 this.afterWorkerSetup(worker)
497
c97c7edb
S
498 return worker
499 }
be0676b3
APA
500
501 /**
ff733df7 502 * This function is the listener registered for each worker message.
be0676b3 503 *
bdacc2d2 504 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
505 */
506 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 507 return message => {
b1989cfd 508 if (message.id != null) {
a3445496 509 // Task execution response received
2740a743 510 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 511 if (promiseResponse != null) {
78cea37e 512 if (message.error != null) {
2740a743 513 promiseResponse.reject(message.error)
a05c10de 514 } else {
2740a743 515 promiseResponse.resolve(message.data as Response)
a05c10de 516 }
2e81254d 517 this.afterTaskExecutionHook(promiseResponse.worker, message)
2740a743 518 this.promiseResponseMap.delete(message.id)
ff733df7
JB
519 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
520 if (
521 this.opts.enableTasksQueue === true &&
416fd65c 522 this.tasksQueueSize(workerNodeKey) > 0
ff733df7 523 ) {
2e81254d
JB
524 this.executeTask(
525 workerNodeKey,
ff733df7
JB
526 this.dequeueTask(workerNodeKey) as Task<Data>
527 )
528 }
be0676b3
APA
529 }
530 }
531 }
be0676b3 532 }
7c0ba920 533
ff733df7
JB
534 private checkAndEmitEvents (): void {
535 if (this.opts.enableEvents === true) {
536 if (this.busy) {
537 this.emitter?.emit(PoolEvents.busy)
538 }
539 if (this.type === PoolType.DYNAMIC && this.full) {
540 this.emitter?.emit(PoolEvents.full)
541 }
164d950a
JB
542 }
543 }
544
0ebe2a9f
JB
545 /**
546 * Sets the given worker node its tasks usage in the pool.
547 *
548 * @param workerNode - The worker node.
549 * @param tasksUsage - The worker node tasks usage.
550 */
551 private setWorkerNodeTasksUsage (
552 workerNode: WorkerNode<Worker, Data>,
553 tasksUsage: TasksUsage
554 ): void {
555 workerNode.tasksUsage = tasksUsage
556 }
557
c923ce56 558 /**
f06e48d8 559 * Gets the given worker its tasks usage in the pool.
c923ce56
JB
560 *
561 * @param worker - The worker.
e2473f60 562 * @throws Error if the worker is not found in the pool worker nodes.
c923ce56
JB
563 * @returns The worker tasks usage.
564 */
05ca3d0d 565 private getWorkerTasksUsage (worker: Worker): TasksUsage {
f06e48d8
JB
566 const workerNodeKey = this.getWorkerNodeKey(worker)
567 if (workerNodeKey !== -1) {
568 return this.workerNodes[workerNodeKey].tasksUsage
ffcbbad8 569 }
f06e48d8 570 throw new Error('Worker could not be found in the pool worker nodes')
a05c10de
JB
571 }
572
573 /**
f06e48d8 574 * Pushes the given worker in the pool worker nodes.
ea7a90d3 575 *
38e795c1 576 * @param worker - The worker.
f06e48d8 577 * @returns The worker nodes length.
ea7a90d3 578 */
f06e48d8
JB
579 private pushWorkerNode (worker: Worker): number {
580 return this.workerNodes.push({
ffcbbad8 581 worker,
f82cd357
JB
582 tasksUsage: {
583 run: 0,
584 running: 0,
585 runTime: 0,
586 runTimeHistory: new CircularArray(),
587 avgRunTime: 0,
588 medRunTime: 0,
589 error: 0
590 },
29ee7e9a 591 tasksQueue: new Queue<Task<Data>>()
ea7a90d3
JB
592 })
593 }
c923ce56
JB
594
595 /**
f06e48d8 596 * Sets the given worker in the pool worker nodes.
c923ce56 597 *
f06e48d8 598 * @param workerNodeKey - The worker node key.
c923ce56
JB
599 * @param worker - The worker.
600 * @param tasksUsage - The worker tasks usage.
f06e48d8 601 * @param tasksQueue - The worker task queue.
c923ce56 602 */
f06e48d8
JB
603 private setWorkerNode (
604 workerNodeKey: number,
c923ce56 605 worker: Worker,
f06e48d8 606 tasksUsage: TasksUsage,
29ee7e9a 607 tasksQueue: Queue<Task<Data>>
c923ce56 608 ): void {
f06e48d8 609 this.workerNodes[workerNodeKey] = {
c923ce56 610 worker,
f06e48d8
JB
611 tasksUsage,
612 tasksQueue
c923ce56
JB
613 }
614 }
51fe3d3c
JB
615
616 /**
f06e48d8 617 * Removes the given worker from the pool worker nodes.
51fe3d3c 618 *
f06e48d8 619 * @param worker - The worker.
51fe3d3c 620 */
416fd65c 621 private removeWorkerNode (worker: Worker): void {
f06e48d8
JB
622 const workerNodeKey = this.getWorkerNodeKey(worker)
623 this.workerNodes.splice(workerNodeKey, 1)
624 this.workerChoiceStrategyContext.remove(workerNodeKey)
51fe3d3c 625 }
adc3c320 626
2e81254d
JB
627 private executeTask (workerNodeKey: number, task: Task<Data>): void {
628 this.beforeTaskExecutionHook(workerNodeKey)
629 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
630 }
631
f9f00b5f 632 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
29ee7e9a 633 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
adc3c320
JB
634 }
635
416fd65c 636 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
29ee7e9a 637 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
adc3c320
JB
638 }
639
416fd65c 640 private tasksQueueSize (workerNodeKey: number): number {
4d8bf9e4 641 return this.workerNodes[workerNodeKey].tasksQueue.size
adc3c320 642 }
ff733df7 643
416fd65c
JB
644 private flushTasksQueue (workerNodeKey: number): void {
645 if (this.tasksQueueSize(workerNodeKey) > 0) {
29ee7e9a
JB
646 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
647 this.executeTask(
648 workerNodeKey,
649 this.dequeueTask(workerNodeKey) as Task<Data>
650 )
ff733df7 651 }
ff733df7
JB
652 }
653 }
654
416fd65c 655 private flushTasksQueueByWorker (worker: Worker): void {
ff733df7
JB
656 const workerNodeKey = this.getWorkerNodeKey(worker)
657 this.flushTasksQueue(workerNodeKey)
658 }
ef41a6e6
JB
659
660 private flushTasksQueues (): void {
661 for (const [workerNodeKey] of this.workerNodes.entries()) {
662 this.flushTasksQueue(workerNodeKey)
663 }
664 }
c97c7edb 665}