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
= {
42 * Workers' virtual task end execution timestamp.
44 private workersVirtualTaskEndTimestamp
: number[] = []
48 pool
: IPool
<Worker
, Data
, Response
>,
49 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
52 this.setTaskStatisticsRequirements(this.opts
)
56 public reset (): boolean {
57 this.workersVirtualTaskEndTimestamp
= []
62 public update (workerNodeKey
: number): boolean {
63 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
68 public choose (): number {
69 let minWorkerVirtualTaskEndTimestamp
= Infinity
70 let chosenWorkerNodeKey
!: number
71 for (const [workerNodeKey
] of this.pool
.workerNodes
.entries()) {
72 if (this.workersVirtualTaskEndTimestamp
[workerNodeKey
] == null) {
73 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
75 const workerVirtualTaskEndTimestamp
=
76 this.workersVirtualTaskEndTimestamp
[workerNodeKey
]
77 if (workerVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
) {
78 minWorkerVirtualTaskEndTimestamp
= workerVirtualTaskEndTimestamp
79 chosenWorkerNodeKey
= workerNodeKey
82 return chosenWorkerNodeKey
86 public remove (workerNodeKey
: number): boolean {
87 this.workersVirtualTaskEndTimestamp
.splice(workerNodeKey
, 1)
92 * Computes the worker node key virtual task end timestamp.
94 * @param workerNodeKey - The worker node key.
96 private computeWorkerVirtualTaskEndTimestamp (workerNodeKey
: number): void {
97 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] =
98 this.getWorkerVirtualTaskEndTimestamp(
100 this.getWorkerVirtualTaskStartTimestamp(workerNodeKey
)
104 private getWorkerVirtualTaskEndTimestamp (
105 workerNodeKey
: number,
106 workerVirtualTaskStartTimestamp
: number
109 workerVirtualTaskStartTimestamp
+ this.getWorkerTaskRunTime(workerNodeKey
)
113 private getWorkerVirtualTaskStartTimestamp (workerNodeKey
: number): number {
116 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] ?? -Infinity