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 * Default worker weight.
54 private readonly defaultWorkerWeight
: number
56 * Worker virtual task runtime.
58 private workerVirtualTaskRunTime
: number = 0
62 pool
: IPool
<Worker
, Data
, Response
>,
63 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
66 this.setTaskStatisticsRequirements(this.opts
)
67 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
71 public reset (): boolean {
72 this.nextWorkerNodeId
= 0
73 this.workerVirtualTaskRunTime
= 0
78 public update (): boolean {
83 public choose (): number {
84 const chosenWorkerNodeKey
= this.nextWorkerNodeId
85 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
87 this.opts
.weights
?.[chosenWorkerNodeKey
] ?? this.defaultWorkerWeight
88 if (workerVirtualTaskRunTime
< workerWeight
) {
89 this.workerVirtualTaskRunTime
=
90 workerVirtualTaskRunTime
+
91 this.getWorkerTaskRunTime(chosenWorkerNodeKey
)
93 this.nextWorkerNodeId
=
94 this.nextWorkerNodeId
=== this.pool
.workerNodes
.length
- 1
96 : this.nextWorkerNodeId
+ 1
97 this.workerVirtualTaskRunTime
= 0
99 return chosenWorkerNodeKey
103 public remove (workerNodeKey
: number): boolean {
104 if (this.nextWorkerNodeId
=== workerNodeKey
) {
105 if (this.pool
.workerNodes
.length
=== 0) {
106 this.nextWorkerNodeId
= 0
107 } else if (this.nextWorkerNodeId
> this.pool
.workerNodes
.length
- 1) {
108 this.nextWorkerNodeId
= this.pool
.workerNodes
.length
- 1
110 this.workerVirtualTaskRunTime
= 0