fix: fix worker choice strategy retries mechanism on some edge cases
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2 import type { IPool } from '../pool'
3 import type { IWorker } from '../worker'
4 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
5 import type {
6 IWorkerChoiceStrategy,
7 StrategyPolicy,
8 WorkerChoiceStrategyOptions
9 } from './selection-strategies-types'
10
11 /**
12 * Selects the least used worker.
13 *
14 * @typeParam Worker - Type of worker which manages the strategy.
15 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
16 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
17 */
18 export class LeastUsedWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
24 implements IWorkerChoiceStrategy {
25 /** @inheritDoc */
26 public readonly strategyPolicy: StrategyPolicy = {
27 dynamicWorkerUsage: false,
28 dynamicWorkerReady: true
29 }
30
31 /** @inheritDoc */
32 public constructor (
33 pool: IPool<Worker, Data, Response>,
34 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
35 ) {
36 super(pool, opts)
37 this.setTaskStatisticsRequirements(this.opts)
38 }
39
40 /** @inheritDoc */
41 public reset (): boolean {
42 return true
43 }
44
45 /** @inheritDoc */
46 public update (): boolean {
47 return true
48 }
49
50 /** @inheritDoc */
51 public choose (): number | undefined {
52 const chosenWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
53 this.assignChosenWorkerNodeKey(chosenWorkerNodeKey)
54 return this.nextWorkerNodeKey
55 }
56
57 /** @inheritDoc */
58 public remove (): boolean {
59 return true
60 }
61
62 private leastUsedNextWorkerNodeKey (): number | undefined {
63 let minNumberOfTasks = Infinity
64 let chosenWorkerNodeKey: number | undefined
65 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
66 const workerTaskStatistics = workerNode.usage.tasks
67 const workerTasks =
68 workerTaskStatistics.executed +
69 workerTaskStatistics.executing +
70 workerTaskStatistics.queued
71 if (this.isWorkerNodeEligible(workerNodeKey) && workerTasks === 0) {
72 chosenWorkerNodeKey = workerNodeKey
73 break
74 } else if (
75 this.isWorkerNodeEligible(workerNodeKey) &&
76 workerTasks < minNumberOfTasks
77 ) {
78 minNumberOfTasks = workerTasks
79 chosenWorkerNodeKey = workerNodeKey
80 }
81 }
82 return chosenWorkerNodeKey
83 }
84 }