1 import type { IWorker
} from
'../worker'
2 import type { IPool
} from
'../pool'
4 DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
,
5 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
7 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
11 TaskStatisticsRequirements
,
12 WorkerChoiceStrategyOptions
13 } from
'./selection-strategies-types'
16 * Selects the next worker with a weighted round robin scheduling algorithm.
17 * Loosely modeled after the weighted round robin queueing algorithm: https://en.wikipedia.org/wiki/Weighted_round_robin.
19 * @typeParam Worker - Type of worker which manages the strategy.
20 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
21 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
23 export class WeightedRoundRobinWorkerChoiceStrategy
<
24 Worker
extends IWorker
,
28 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
29 implements IWorkerChoiceStrategy
{
31 public readonly strategyPolicy
: StrategyPolicy
= {
32 useDynamicWorker
: true
36 public readonly taskStatisticsRequirements
: TaskStatisticsRequirements
= {
42 waitTime
: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
,
43 elu
: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
47 * Default worker weight.
49 private readonly defaultWorkerWeight
: number
51 * Worker virtual task runtime.
53 private workerVirtualTaskRunTime
: number = 0
57 pool
: IPool
<Worker
, Data
, Response
>,
58 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
61 this.setTaskStatisticsRequirements(this.opts
)
62 this.defaultWorkerWeight
= this.computeDefaultWorkerWeight()
66 public reset (): boolean {
67 this.nextWorkerNodeKey
= 0
68 this.workerVirtualTaskRunTime
= 0
73 public update (): boolean {
78 public choose (): number {
79 const chosenWorkerNodeKey
= this.nextWorkerNodeKey
81 this.weightedRoundRobinNextWorkerNodeKey()
82 } while (!this.isWorkerNodeReady(this.nextWorkerNodeKey
))
83 return chosenWorkerNodeKey
87 public remove (workerNodeKey
: number): boolean {
88 if (this.nextWorkerNodeKey
=== workerNodeKey
) {
89 if (this.pool
.workerNodes
.length
=== 0) {
90 this.nextWorkerNodeKey
= 0
91 } else if (this.nextWorkerNodeKey
> this.pool
.workerNodes
.length
- 1) {
92 this.nextWorkerNodeKey
= this.pool
.workerNodes
.length
- 1
94 this.workerVirtualTaskRunTime
= 0
99 private weightedRoundRobinNextWorkerNodeKey (): number {
100 const workerVirtualTaskRunTime
= this.workerVirtualTaskRunTime
102 this.opts
.weights
?.[this.nextWorkerNodeKey
] ?? this.defaultWorkerWeight
103 if (workerVirtualTaskRunTime
< workerWeight
) {
104 this.workerVirtualTaskRunTime
=
105 workerVirtualTaskRunTime
+
106 this.getWorkerTaskRunTime(this.nextWorkerNodeKey
)
108 this.nextWorkerNodeKey
=
109 this.nextWorkerNodeKey
=== this.pool
.workerNodes
.length
- 1
111 : this.nextWorkerNodeKey
+ 1
112 this.workerVirtualTaskRunTime
= 0
114 return this.nextWorkerNodeKey