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
= {
42 * Worker node id where the current task will be submitted.
44 private currentWorkerNodeId
: number = 0
46 * Default worker weight.
48 private readonly defaultWorkerWeight
: number
50 * Worker virtual task runtime.
52 private workerVirtualTaskRunTime
: number = 0
56 pool
: IPool
<Worker
, Data
, Response
>,
57 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
60 this.setTaskStatisticsRequirements(this.opts
)
61 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
65 public reset (): boolean {
66 this.currentWorkerNodeId
= 0
67 this.workerVirtualTaskRunTime
= 0
72 public update (): boolean {
77 public choose (): number {
78 const chosenWorkerNodeKey
= this.currentWorkerNodeId
79 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
81 this.opts
.weights
?.[chosenWorkerNodeKey
] ?? this.defaultWorkerWeight
82 if (workerVirtualTaskRunTime
< workerWeight
) {
83 this.workerVirtualTaskRunTime
=
84 workerVirtualTaskRunTime
+
85 this.getWorkerTaskRunTime(chosenWorkerNodeKey
)
87 this.currentWorkerNodeId
=
88 this.currentWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
90 : this.currentWorkerNodeId
+ 1
91 this.workerVirtualTaskRunTime
= 0
93 return chosenWorkerNodeKey
97 public remove (workerNodeKey
: number): boolean {
98 if (this.currentWorkerNodeId
=== workerNodeKey
) {
99 if (this.pool
.workerNodes
.length
=== 0) {
100 this.currentWorkerNodeId
= 0
101 } else if (this.currentWorkerNodeId
> this.pool
.workerNodes
.length
- 1) {
102 this.currentWorkerNodeId
= this.pool
.workerNodes
.length
- 1
104 this.workerVirtualTaskRunTime
= 0