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'
7 WorkerChoiceStrategyOptions
8 } from
'./selection-strategies-types'
11 * Selects the least used worker.
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
15 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
17 export class LeastUsedWorkerChoiceStrategy
<
18 Worker
extends IWorker
,
22 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
23 implements IWorkerChoiceStrategy
{
26 pool
: IPool
<Worker
, Data
, Response
>,
27 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
30 this.setTaskStatisticsRequirements(this.opts
)
34 public reset (): boolean {
39 public update (): boolean {
44 public choose (): number | undefined {
45 this.nextWorkerNodeKey
= this.leastUsedNextWorkerNodeKey()
46 return this.nextWorkerNodeKey
50 public remove (): boolean {
54 private leastUsedNextWorkerNodeKey (): number | undefined {
55 let minNumberOfTasks
= Infinity
56 let chosenWorkerNodeKey
: number | undefined
57 for (const [workerNodeKey
, workerNode
] of this.pool
.workerNodes
.entries()) {
58 if (!this.isWorkerNodeEligible(workerNodeKey
)) {
61 const workerTaskStatistics
= workerNode
.usage
.tasks
63 workerTaskStatistics
.executed
+
64 workerTaskStatistics
.executing
+
65 workerTaskStatistics
.queued
66 if (workerTasks
=== 0) {
67 chosenWorkerNodeKey
= workerNodeKey
69 } else if (workerTasks
< minNumberOfTasks
) {
70 minNumberOfTasks
= workerTasks
71 chosenWorkerNodeKey
= workerNodeKey
74 return chosenWorkerNodeKey