1 import type { IWorker
} from
'../worker'
2 import type { IPool
} from
'../pool'
3 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
} from
'../../utils'
4 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
7 TaskStatisticsRequirements
,
8 WorkerChoiceStrategyOptions
9 } from
'./selection-strategies-types'
12 * Selects the next worker with a weighted round robin scheduling algorithm.
13 * Loosely modeled after the weighted round robin queueing algorithm: https://en.wikipedia.org/wiki/Weighted_round_robin.
15 * @typeParam Worker - Type of worker which manages the strategy.
16 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
17 * @typeParam Response - Type of execution response. This can only be serializable data.
19 export class WeightedRoundRobinWorkerChoiceStrategy
<
20 Worker
extends IWorker
,
24 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
25 implements IWorkerChoiceStrategy
{
27 public readonly taskStatisticsRequirements
: TaskStatisticsRequirements
= {
46 * Worker node id where the current task will be submitted.
48 private currentWorkerNodeId
: number = 0
50 * Default worker weight.
52 private readonly defaultWorkerWeight
: number
54 * Worker virtual task runtime.
56 private workerVirtualTaskRunTime
: number = 0
60 pool
: IPool
<Worker
, Data
, Response
>,
61 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
64 this.setTaskStatisticsRequirements(this.opts
)
65 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
69 public reset (): boolean {
70 this.currentWorkerNodeId
= 0
71 this.workerVirtualTaskRunTime
= 0
76 public update (): boolean {
81 public choose (): number {
82 const chosenWorkerNodeKey
= this.currentWorkerNodeId
83 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
85 this.opts
.weights
?.[chosenWorkerNodeKey
] ?? this.defaultWorkerWeight
86 if (workerVirtualTaskRunTime
< workerWeight
) {
87 this.workerVirtualTaskRunTime
=
88 workerVirtualTaskRunTime
+
89 this.getWorkerTaskRunTime(chosenWorkerNodeKey
)
91 this.currentWorkerNodeId
=
92 this.currentWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
94 : this.currentWorkerNodeId
+ 1
95 this.workerVirtualTaskRunTime
= 0
97 return chosenWorkerNodeKey
101 public remove (workerNodeKey
: number): boolean {
102 if (this.currentWorkerNodeId
=== workerNodeKey
) {
103 if (this.pool
.workerNodes
.length
=== 0) {
104 this.currentWorkerNodeId
= 0
105 } else if (this.currentWorkerNodeId
> this.pool
.workerNodes
.length
- 1) {
106 this.currentWorkerNodeId
= this.pool
.workerNodes
.length
- 1
108 this.workerVirtualTaskRunTime
= 0