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'
8 TaskStatisticsRequirements
,
9 WorkerChoiceStrategyOptions
10 } from
'./selection-strategies-types'
13 * Selects the next worker with a weighted round robin scheduling algorithm.
14 * Loosely modeled after the weighted round robin queueing algorithm: https://en.wikipedia.org/wiki/Weighted_round_robin.
16 * @typeParam Worker - Type of worker which manages the strategy.
17 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
18 * @typeParam Response - Type of execution response. This can only be serializable data.
20 export class WeightedRoundRobinWorkerChoiceStrategy
<
21 Worker
extends IWorker
,
25 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
26 implements IWorkerChoiceStrategy
{
28 public readonly strategyPolicy
: StrategyPolicy
= {
29 useDynamicWorker
: true
33 public readonly taskStatisticsRequirements
: TaskStatisticsRequirements
= {
52 * Worker node id where the current task will be submitted.
54 private currentWorkerNodeId
: number = 0
56 * Default worker weight.
58 private readonly defaultWorkerWeight
: number
60 * Worker virtual task runtime.
62 private workerVirtualTaskRunTime
: number = 0
66 pool
: IPool
<Worker
, Data
, Response
>,
67 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
70 this.setTaskStatisticsRequirements(this.opts
)
71 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
75 public reset (): boolean {
76 this.currentWorkerNodeId
= 0
77 this.workerVirtualTaskRunTime
= 0
82 public update (): boolean {
87 public choose (): number {
88 const chosenWorkerNodeKey
= this.currentWorkerNodeId
89 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
91 this.opts
.weights
?.[chosenWorkerNodeKey
] ?? this.defaultWorkerWeight
92 if (workerVirtualTaskRunTime
< workerWeight
) {
93 this.workerVirtualTaskRunTime
=
94 workerVirtualTaskRunTime
+
95 this.getWorkerTaskRunTime(chosenWorkerNodeKey
)
97 this.currentWorkerNodeId
=
98 this.currentWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
100 : this.currentWorkerNodeId
+ 1
101 this.workerVirtualTaskRunTime
= 0
103 return chosenWorkerNodeKey
107 public remove (workerNodeKey
: number): boolean {
108 if (this.currentWorkerNodeId
=== workerNodeKey
) {
109 if (this.pool
.workerNodes
.length
=== 0) {
110 this.currentWorkerNodeId
= 0
111 } else if (this.currentWorkerNodeId
> this.pool
.workerNodes
.length
- 1) {
112 this.currentWorkerNodeId
= this.pool
.workerNodes
.length
- 1
114 this.workerVirtualTaskRunTime
= 0