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'
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 requiredStatistics
: RequiredStatistics
= {
37 * Workers' virtual task end execution timestamp.
39 private workersVirtualTaskEndTimestamp
: number[] = []
43 pool
: IPool
<Worker
, Data
, Response
>,
44 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
47 this.setRequiredStatistics(this.opts
)
51 public reset (): boolean {
52 this.workersVirtualTaskEndTimestamp
= []
57 public update (workerNodeKey
: number): boolean {
58 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
63 public choose (): number {
64 let minWorkerVirtualTaskEndTimestamp
= Infinity
65 let chosenWorkerNodeKey
!: number
66 for (const [workerNodeKey
] of this.pool
.workerNodes
.entries()) {
67 if (this.workersVirtualTaskEndTimestamp
[workerNodeKey
] == null) {
68 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
70 const workerVirtualTaskEndTimestamp
=
71 this.workersVirtualTaskEndTimestamp
[workerNodeKey
]
72 if (workerVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
) {
73 minWorkerVirtualTaskEndTimestamp
= workerVirtualTaskEndTimestamp
74 chosenWorkerNodeKey
= workerNodeKey
77 return chosenWorkerNodeKey
81 public remove (workerNodeKey
: number): boolean {
82 this.workersVirtualTaskEndTimestamp
.splice(workerNodeKey
, 1)
87 * Computes the worker node key virtual task end timestamp.
89 * @param workerNodeKey - The worker node key.
91 private computeWorkerVirtualTaskEndTimestamp (workerNodeKey
: number): void {
92 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] =
93 this.getWorkerVirtualTaskEndTimestamp(
95 this.getWorkerVirtualTaskStartTimestamp(workerNodeKey
)
99 private getWorkerVirtualTaskEndTimestamp (
100 workerNodeKey
: number,
101 workerVirtualTaskStartTimestamp
: number
104 workerVirtualTaskStartTimestamp
+ this.getWorkerTaskRunTime(workerNodeKey
)
108 private getWorkerVirtualTaskStartTimestamp (workerNodeKey
: number): number {
111 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] ?? -Infinity