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 taskStatistics
: TaskStatistics
= {
38 * Workers' virtual task end execution timestamp.
40 private workersVirtualTaskEndTimestamp
: number[] = []
44 pool
: IPool
<Worker
, Data
, Response
>,
45 opts
: WorkerChoiceStrategyOptions
= DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
48 this.setTaskStatistics(this.opts
)
52 public reset (): boolean {
53 this.workersVirtualTaskEndTimestamp
= []
58 public update (workerNodeKey
: number): boolean {
59 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
64 public choose (): number {
65 let minWorkerVirtualTaskEndTimestamp
= Infinity
66 let chosenWorkerNodeKey
!: number
67 for (const [workerNodeKey
] of this.pool
.workerNodes
.entries()) {
68 if (this.workersVirtualTaskEndTimestamp
[workerNodeKey
] == null) {
69 this.computeWorkerVirtualTaskEndTimestamp(workerNodeKey
)
71 const workerVirtualTaskEndTimestamp
=
72 this.workersVirtualTaskEndTimestamp
[workerNodeKey
]
73 if (workerVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
) {
74 minWorkerVirtualTaskEndTimestamp
= workerVirtualTaskEndTimestamp
75 chosenWorkerNodeKey
= workerNodeKey
78 return chosenWorkerNodeKey
82 public remove (workerNodeKey
: number): boolean {
83 this.workersVirtualTaskEndTimestamp
.splice(workerNodeKey
, 1)
88 * Computes the worker node key virtual task end timestamp.
90 * @param workerNodeKey - The worker node key.
92 private computeWorkerVirtualTaskEndTimestamp (workerNodeKey
: number): void {
93 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] =
94 this.getWorkerVirtualTaskEndTimestamp(
96 this.getWorkerVirtualTaskStartTimestamp(workerNodeKey
)
100 private getWorkerVirtualTaskEndTimestamp (
101 workerNodeKey
: number,
102 workerVirtualTaskStartTimestamp
: number
105 workerVirtualTaskStartTimestamp
+ this.getWorkerTaskRunTime(workerNodeKey
)
109 private getWorkerVirtualTaskStartTimestamp (workerNodeKey
: number): number {
112 this.workersVirtualTaskEndTimestamp
[workerNodeKey
] ?? -Infinity