1 import type { IWorker
} from
'../worker'
2 import type { IPool
} from
'../pool'
3 import { DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
} from
'../../utils'
4 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
7 InternalWorkerChoiceStrategyOptions
,
8 TaskStatisticsRequirements
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 structured-cloneable data.
17 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
19 export class WeightedRoundRobinWorkerChoiceStrategy
<
20 Worker
extends IWorker
,
24 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
25 implements IWorkerChoiceStrategy
{
27 public readonly taskStatisticsRequirements
: TaskStatisticsRequirements
= {
33 waitTime
: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
,
34 elu
: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
38 * Worker node virtual task runtime.
40 private workerNodeVirtualTaskRunTime
: number = 0
44 pool
: IPool
<Worker
, Data
, Response
>,
45 opts
: InternalWorkerChoiceStrategyOptions
48 this.setTaskStatisticsRequirements(this.opts
)
52 public reset (): boolean {
53 this.resetWorkerNodeKeyProperties()
54 this.workerNodeVirtualTaskRunTime
= 0
59 public update (): boolean {
64 public choose (): number | undefined {
65 this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey
)
66 this.weightedRoundRobinNextWorkerNodeKey()
67 this.checkNextWorkerNodeReadiness()
68 return this.nextWorkerNodeKey
72 public remove (workerNodeKey
: number): boolean {
73 if (this.pool
.workerNodes
.length
=== 0) {
76 if (this.nextWorkerNodeKey
=== workerNodeKey
) {
77 this.workerNodeVirtualTaskRunTime
= 0
78 if (this.nextWorkerNodeKey
> this.pool
.workerNodes
.length
- 1) {
79 this.nextWorkerNodeKey
= this.pool
.workerNodes
.length
- 1
83 this.previousWorkerNodeKey
=== workerNodeKey
&&
84 this.previousWorkerNodeKey
> this.pool
.workerNodes
.length
- 1
86 this.previousWorkerNodeKey
= this.pool
.workerNodes
.length
- 1
91 private weightedRoundRobinNextWorkerNodeKey (): number | undefined {
92 const workerWeight
= this.opts
.weights
?.[
93 this.nextWorkerNodeKey
?? this.previousWorkerNodeKey
95 if (this.workerNodeVirtualTaskRunTime
< workerWeight
) {
96 this.workerNodeVirtualTaskRunTime
=
97 this.workerNodeVirtualTaskRunTime
+
98 this.getWorkerNodeTaskRunTime(
99 this.nextWorkerNodeKey
?? this.previousWorkerNodeKey
102 this.nextWorkerNodeKey
=
103 this.nextWorkerNodeKey
=== this.pool
.workerNodes
.length
- 1
105 : (this.nextWorkerNodeKey
?? this.previousWorkerNodeKey
) + 1
106 this.workerNodeVirtualTaskRunTime
= 0
108 return this.nextWorkerNodeKey