1 import type { IWorker
} from
'../worker'
2 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
6 } from
'./selection-strategies-types'
9 * Worker virtual task timestamp.
11 interface WorkerVirtualTaskTimestamp
{
17 * Selects the next worker with a fair share scheduling algorithm.
18 * Loosely modeled after the fair queueing algorithm: https://en.wikipedia.org/wiki/Fair_queuing.
20 * @typeParam Worker - Type of worker which manages the strategy.
21 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
22 * @typeParam Response - Type of response of execution. This can only be serializable data.
24 export class FairShareWorkerChoiceStrategy
<
25 Worker
extends IWorker
,
29 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
30 implements IWorkerChoiceStrategy
{
32 public readonly requiredStatistics
: RequiredStatistics
= {
39 * Worker last virtual task execution timestamp.
41 private readonly workerLastVirtualTaskTimestamp
: Map
<
43 WorkerVirtualTaskTimestamp
44 > = new Map
<number, WorkerVirtualTaskTimestamp
>()
47 public reset (): boolean {
48 this.workerLastVirtualTaskTimestamp
.clear()
53 public choose (): number {
54 let minWorkerVirtualTaskEndTimestamp
= Infinity
55 let chosenWorkerNodeKey
!: number
56 for (const [index
] of this.pool
.workerNodes
.entries()) {
57 this.computeWorkerLastVirtualTaskTimestamp(index
)
58 const workerLastVirtualTaskEndTimestamp
=
59 this.workerLastVirtualTaskTimestamp
.get(index
)?.end
?? 0
61 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
63 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
64 chosenWorkerNodeKey
= index
67 return chosenWorkerNodeKey
71 public remove (workerNodeKey
: number): boolean {
72 const deleted
= this.workerLastVirtualTaskTimestamp
.delete(workerNodeKey
)
73 for (const [key
, value
] of this.workerLastVirtualTaskTimestamp
.entries()) {
74 if (key
> workerNodeKey
) {
75 this.workerLastVirtualTaskTimestamp
.set(key
- 1, value
)
82 * Computes worker last virtual task timestamp.
84 * @param workerNodeKey - The worker node key.
86 private computeWorkerLastVirtualTaskTimestamp (workerNodeKey
: number): void {
87 const workerVirtualTaskStartTimestamp
= Math.max(
89 this.workerLastVirtualTaskTimestamp
.get(workerNodeKey
)?.end
?? -Infinity
91 const workerVirtualTaskTRunTime
= this.requiredStatistics
.medRunTime
92 ? this.pool
.workerNodes
[workerNodeKey
].tasksUsage
.medRunTime
93 : this.pool
.workerNodes
[workerNodeKey
].tasksUsage
.avgRunTime
94 this.workerLastVirtualTaskTimestamp
.set(workerNodeKey
, {
95 start
: workerVirtualTaskStartTimestamp
,
96 end
: workerVirtualTaskStartTimestamp
+ (workerVirtualTaskTRunTime
?? 0)