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
{
32 public readonly requiredStatistics
: RequiredStatistics
= {
37 * Worker last virtual task execution timestamp.
39 private readonly workerLastVirtualTaskTimestamp
: Map
<
41 WorkerVirtualTaskTimestamp
42 > = new Map
<number, WorkerVirtualTaskTimestamp
>()
45 public reset (): boolean {
46 this.workerLastVirtualTaskTimestamp
.clear()
51 public choose (): number {
52 let minWorkerVirtualTaskEndTimestamp
= Infinity
53 let chosenWorkerKey
!: number
54 for (const [index
] of this.pool
.workers
.entries()) {
55 this.computeWorkerLastVirtualTaskTimestamp(index
)
56 const workerLastVirtualTaskEndTimestamp
=
57 this.workerLastVirtualTaskTimestamp
.get(index
)?.end
?? 0
59 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
61 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
62 chosenWorkerKey
= index
65 return chosenWorkerKey
69 public remove (workerKey
: number): boolean {
70 const workerDeleted
= this.workerLastVirtualTaskTimestamp
.delete(workerKey
)
71 for (const [key
, value
] of this.workerLastVirtualTaskTimestamp
.entries()) {
72 if (key
> workerKey
) {
73 this.workerLastVirtualTaskTimestamp
.set(key
- 1, value
)
80 * Computes worker last virtual task timestamp.
82 * @param workerKey - The worker key.
84 private computeWorkerLastVirtualTaskTimestamp (workerKey
: number): void {
85 const workerVirtualTaskStartTimestamp
= Math.max(
87 this.workerLastVirtualTaskTimestamp
.get(workerKey
)?.end
?? -Infinity
89 this.workerLastVirtualTaskTimestamp
.set(workerKey
, {
90 start
: workerVirtualTaskStartTimestamp
,
92 workerVirtualTaskStartTimestamp
+
93 (this.pool
.workers
[workerKey
].tasksUsage
.avgRunTime
?? 0)