1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
} from
'../../utils'
2 import type { IPool
} from
'../pool'
3 import type { IWorker
} from
'../worker'
4 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
7 TaskStatisticsRequirements
,
8 WorkerChoiceStrategyOptions
9 } from
'./selection-strategies-types'
12 * Selects the next worker with a fair share scheduling algorithm.
13 * Loosely modeled after the fair queueing algorithm: https://en.wikipedia.org/wiki/Fair_queuing.
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 FairShareWorkerChoiceStrategy
<
20 Worker
extends IWorker
,
24 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
25 implements IWorkerChoiceStrategy
{
27 public readonly taskStatisticsRequirements
: TaskStatisticsRequirements
= {
46 * Workers' virtual task end execution timestamp.
48 private workersVirtualTaskEndTimestamp
: number[] = []
52 pool
: IPool
<Worker
, Data
, Response
>,
53 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
56 this.setTaskStatisticsRequirements(this.opts
)
60 public reset (): boolean {
61 this.workersVirtualTaskEndTimestamp
= []
66 public update (workerNodeKey
: number): boolean {
67 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
72 public choose (): number {
73 let minWorkerVirtualTaskEndTimestamp
= Infinity
74 let chosenWorkerNodeKey
!: number
75 for (const [workerNodeKey
] of this.pool
.workerNodes
.entries()) {
76 if (this.workersVirtualTaskEndTimestamp
[workerNodeKey
] == null) {
77 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
79 const workerVirtualTaskEndTimestamp
=
80 this.workersVirtualTaskEndTimestamp
[workerNodeKey
]
81 if (workerVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
) {
82 minWorkerVirtualTaskEndTimestamp
= workerVirtualTaskEndTimestamp
83 chosenWorkerNodeKey
= workerNodeKey
86 return chosenWorkerNodeKey
90 public remove (workerNodeKey
: number): boolean {
91 this.workersVirtualTaskEndTimestamp
.splice(workerNodeKey
, 1)
96 * Computes the worker node key virtual task end timestamp.
98 * @param workerNodeKey - The worker node key.
100 private computeWorkerVirtualTaskEndTimestamp (workerNodeKey
: number): void {
101 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] =
102 this.getWorkerVirtualTaskEndTimestamp(
104 this.getWorkerVirtualTaskStartTimestamp(workerNodeKey
)
108 private getWorkerVirtualTaskEndTimestamp (
109 workerNodeKey
: number,
110 workerVirtualTaskStartTimestamp
: number
113 workerVirtualTaskStartTimestamp
+ this.getWorkerTaskRunTime(workerNodeKey
)
117 private getWorkerVirtualTaskStartTimestamp (workerNodeKey
: number): number {
120 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] ?? -Infinity