1 import type { IPoolWorker
} from
'../pool-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 IPoolWorker
,
29 extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
>
30 implements IWorkerChoiceStrategy
<Worker
, Data
, Response
> {
32 public readonly requiredStatistics
: RequiredStatistics
= {
38 * Worker last virtual task execution timestamp.
40 private readonly workerLastVirtualTaskTimestamp
: Map
<
42 WorkerVirtualTaskTimestamp
43 > = new Map
<number, WorkerVirtualTaskTimestamp
>()
46 public reset (): boolean {
47 this.workerLastVirtualTaskTimestamp
.clear()
52 public choose (): number {
53 let minWorkerVirtualTaskEndTimestamp
= Infinity
54 let chosenWorkerKey
!: number
55 for (const [index
] of this.pool
.workers
.entries()) {
56 this.computeWorkerLastVirtualTaskTimestamp(index
)
57 const workerLastVirtualTaskEndTimestamp
=
58 this.workerLastVirtualTaskTimestamp
.get(index
)?.end
?? 0
60 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
62 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
63 chosenWorkerKey
= index
66 return chosenWorkerKey
70 public remove (workerKey
: number): boolean {
71 const workerDeleted
= this.workerLastVirtualTaskTimestamp
.delete(workerKey
)
72 for (const [key
, value
] of this.workerLastVirtualTaskTimestamp
.entries()) {
73 if (key
> workerKey
) {
74 this.workerLastVirtualTaskTimestamp
.set(key
- 1, value
)
81 * Computes worker last virtual task timestamp.
83 * @param workerKey - The worker key.
85 private computeWorkerLastVirtualTaskTimestamp (workerKey
: number): void {
86 const workerVirtualTaskStartTimestamp
= Math.max(
88 this.workerLastVirtualTaskTimestamp
.get(workerKey
)?.end
?? -Infinity
90 this.workerLastVirtualTaskTimestamp
.set(workerKey
, {
91 start
: workerVirtualTaskStartTimestamp
,
93 workerVirtualTaskStartTimestamp
+
94 (this.pool
.workers
[workerKey
].tasksUsage
.avgRunTime
?? 0)