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
<Worker
, WorkerVirtualTaskTimestamp
>()
40 public reset (): boolean {
41 this.workerLastVirtualTaskTimestamp
.clear()
46 public choose (): Worker
{
47 let minWorkerVirtualTaskEndTimestamp
= Infinity
48 let chosenWorker
!: Worker
49 for (const value
of this.pool
.workers
.values()) {
50 const worker
= value
.worker
51 this.computeWorkerLastVirtualTaskTimestamp(worker
)
52 const workerLastVirtualTaskEndTimestamp
=
53 this.workerLastVirtualTaskTimestamp
.get(worker
)?.end
?? 0
55 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
57 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
65 * Computes worker last virtual task timestamp.
67 * @param worker - The worker.
69 private computeWorkerLastVirtualTaskTimestamp (worker
: Worker
): void {
70 const workerVirtualTaskStartTimestamp
= Math.max(
72 this.workerLastVirtualTaskTimestamp
.get(worker
)?.end
?? -Infinity
74 this.workerLastVirtualTaskTimestamp
.set(worker
, {
75 start
: workerVirtualTaskStartTimestamp
,
77 workerVirtualTaskStartTimestamp
+
78 (this.pool
.getWorkerAverageTasksRunTime(worker
) ?? 0)