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 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 requiredStatistics
: RequiredStatistics
= {
38 * Worker node id where the current task will be submitted.
40 private currentWorkerNodeId
: number = 0
42 * Default worker weight.
44 private readonly defaultWorkerWeight
: number
46 * Worker virtual task runtime.
48 private workerVirtualTaskRunTime
: number = 0
52 pool
: IPool
<Worker
, Data
, Response
>,
53 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
56 this.setRequiredStatistics(this.opts
)
57 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
61 public reset (): boolean {
62 this.currentWorkerNodeId
= 0
63 this.workerVirtualTaskRunTime
= 0
68 public update (): boolean {
73 public choose (): number {
74 const chosenWorkerNodeKey
= this.currentWorkerNodeId
75 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
77 this.opts
.weights
?.[chosenWorkerNodeKey
] ?? this.defaultWorkerWeight
78 if (workerVirtualTaskRunTime
< workerWeight
) {
79 this.workerVirtualTaskRunTime
=
80 workerVirtualTaskRunTime
+
81 this.getWorkerTaskRunTime(chosenWorkerNodeKey
)
83 this.currentWorkerNodeId
=
84 this.currentWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
86 : this.currentWorkerNodeId
+ 1
87 this.workerVirtualTaskRunTime
= 0
89 return chosenWorkerNodeKey
93 public remove (workerNodeKey
: number): boolean {
94 if (this.currentWorkerNodeId
=== workerNodeKey
) {
95 if (this.pool
.workerNodes
.length
=== 0) {
96 this.currentWorkerNodeId
= 0
97 } else if (this.currentWorkerNodeId
> this.pool
.workerNodes
.length
- 1) {
98 this.currentWorkerNodeId
= this.pool
.workerNodes
.length
- 1
100 this.workerVirtualTaskRunTime
= 0