1 import type { IPoolWorker
} from
'../pool-worker'
2 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
3 import type { RequiredStatistics
} from
'./selection-strategies-types'
6 * Worker virtual task timestamp.
8 interface WorkerVirtualTaskTimestamp
{
14 * Selects the next worker with a fair share scheduling algorithm.
15 * Loosely modeled after the fair queueing algorithm: https://en.wikipedia.org/wiki/Fair_queuing.
17 * @typeParam Worker - Type of worker which manages the strategy.
18 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
19 * @typeParam Response - Type of response of execution. This can only be serializable data.
21 export class FairShareWorkerChoiceStrategy
<
22 Worker
extends IPoolWorker
,
25 > extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
> {
27 public readonly requiredStatistics
: RequiredStatistics
= {
32 * Worker last virtual task execution timestamp.
34 private readonly workerLastVirtualTaskTimestamp
: Map
<
36 WorkerVirtualTaskTimestamp
37 > = new Map
<number, WorkerVirtualTaskTimestamp
>()
40 public reset (): boolean {
41 this.workerLastVirtualTaskTimestamp
.clear()
46 public choose (): number {
47 let minWorkerVirtualTaskEndTimestamp
= Infinity
48 let chosenWorkerKey
!: number
49 for (const [index
] of this.pool
.workers
.entries()) {
50 this.computeWorkerLastVirtualTaskTimestamp(index
)
51 const workerLastVirtualTaskEndTimestamp
=
52 this.workerLastVirtualTaskTimestamp
.get(index
)?.end
?? 0
54 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
56 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
57 chosenWorkerKey
= index
60 return chosenWorkerKey
64 public remove (workerKey
: number): boolean {
65 const workerDeleted
= this.workerLastVirtualTaskTimestamp
.delete(workerKey
)
66 for (const [key
, value
] of this.workerLastVirtualTaskTimestamp
.entries()) {
67 if (key
> workerKey
) {
68 this.workerLastVirtualTaskTimestamp
.set(key
- 1, value
)
75 * Computes worker last virtual task timestamp.
77 * @param workerKey - The worker key.
79 private computeWorkerLastVirtualTaskTimestamp (workerKey
: number): void {
80 const workerVirtualTaskStartTimestamp
= Math.max(
82 this.workerLastVirtualTaskTimestamp
.get(workerKey
)?.end
?? -Infinity
84 this.workerLastVirtualTaskTimestamp
.set(workerKey
, {
85 start
: workerVirtualTaskStartTimestamp
,
87 workerVirtualTaskStartTimestamp
+
88 (this.pool
.workers
[workerKey
].tasksUsage
.avgRunTime
?? 0)