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'
8 WorkerChoiceStrategyOptions
9 } from
'./selection-strategies-types'
12 * Selects the least used worker.
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.
18 export class LeastUsedWorkerChoiceStrategy
<
19 Worker
extends IWorker
,
23 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
24 implements IWorkerChoiceStrategy
{
26 public readonly strategyPolicy
: StrategyPolicy
= {
27 dynamicWorkerUsage
: false,
28 dynamicWorkerReady
: true
33 pool
: IPool
<Worker
, Data
, Response
>,
34 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
37 this.setTaskStatisticsRequirements(this.opts
)
41 public reset (): boolean {
46 public update (): boolean {
51 public choose (): number | undefined {
52 const chosenWorkerNodeKey
= this.leastUsedNextWorkerNodeKey()
53 this.assignChosenWorkerNodeKey(chosenWorkerNodeKey
)
54 return this.nextWorkerNodeKey
58 public remove (): boolean {
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
68 workerTaskStatistics
.executed
+
69 workerTaskStatistics
.executing
+
70 workerTaskStatistics
.queued
71 if (this.isWorkerNodeEligible(workerNodeKey
) && workerTasks
=== 0) {
72 chosenWorkerNodeKey
= workerNodeKey
75 this.isWorkerNodeEligible(workerNodeKey
) &&
76 workerTasks
< minNumberOfTasks
78 minNumberOfTasks
= workerTasks
79 chosenWorkerNodeKey
= workerNodeKey
82 return chosenWorkerNodeKey